Local Variables in Lambda Expressions
[code:c#]
int a = 0;
Action action = () => Console.WriteLine(a);
action();
[/code]
[code:c#]
[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
public int a;
public void <Main>b__0()
{
Console.WriteLine(this.a);
}
}
void Main()
{
int a = 0;
var display = new <>c__DisplayClass1();
display.a = a;
var action = new Action(display.<Main>b__0);
action();
}
[/code]
If we take this slightly different sample :
[code:c#]
int a = 0;
Action action = () => Console.WriteLine(a);
a = 42;
action();
[/code]
Actually, this latter piece of code is expanded like this:
[code:c#]
var display = new <>c__DisplayClass1();
display.a = 0;
var action = new Action(display.<Main>b__0);
display.a = 42;
action();
[/code]
This is quite simple actually, but we can feel that the "magic" behind the C# 3.0 syntactic sugar is the result of a lot of thinking !
I will end this post by a big thanks to Eric Lippert, who took the time to answer me, even though he's probably under heavy load with the developement of C# 4.0. (With the contravariance of generics, yey !)