I have this code, which works as I wanted but I don\'t understand exactly why. Thinking about a stack in C, C++, I\'d guess that the p variable will be on the stack on each call
Lambdas are just glorified anonymous delegates
Rick's article describes how the compiler generates a class that handles the enumTest p
value and delegate
.
Also good info at Where does anonymous function body variables saved ?
Basically the compiler creates a new instance of the "closure class" with local variables that must be passed to lambda. This is why you output is correct.
UPDATE
In the case of:
for (int i=0; i<10; i++)
{
var t = new Thread(() => { Console.WriteLine(i); });
t.Start();
}
The variable i
is shared between the for
and the lambda
. Each thread is accessing the same i
. And since the for loop tends to finsih before any thread runs, all you see is '10'.
See http://msdn.microsoft.com/en-us/library/0yw3tz5k(v=vs.80).aspx