Could someone tell me how does it work? I would be grateful. Dunno how to debug this.
using System;
class Prg
{
private static Func<double, Func<double, double>> Add(int c)
{
return x => y => x + y++ + (c *= 2);
}
public static void Main(string[] args)
{
int a = 1;
int b = 100;
var F = Add(2);
var G = F(a);
G(b);
Console.WriteLine(G(b));
}
}
EDIT: I have got another one if you want to enjoy our C# exam.. Here is the code.
delegate int F();
class Prg { int a = 10;
public F Adder(int x) {
int i = x;
return delegate {
return a += i++; };
}
static void Main() {
Prg p = new Prg();
F f = p.Adder(5);
p.Adder(10);
f();
System.Console.Write(f());
} }
I will start with: don’t write such code, ever.
And if you really want to know what is happening:
var F = Add(2), method Add() creates and returns a lambda expression with c==2. What is important here, is thatcis caught by lambda (you can read about capturing variables on msdn.var G = F(x)you are simply calling your function with parametera = 1and you get another function as a result,double -> doubleto be exact.G(b)you are calling your function, exactly this one:x + y++ + (c *= 2);Now:Console....you are invoking your function again. This time, parameter is again equal to100, so a result would be identical, but your captured variablecis now equal to 4, so a result you receive1 + (100+) + (4 *= 2) -> 1 + 100 + 8 -> 109Here’s a short example that might shine some light on what has happened there: