<sj******@yahoo.comwrote:
Can someone clarify what is happening in these 2 code fragments ?
int i=0;
Action b = delegate {i++; Console.WriteLine("Within b() i= +
i.ToString());};
Action<inta = delegate(int j){ j++; Console.WriteLine("Within a(i) =
" + j.ToString());};
i++;
b();
// i now becomes 2
a(i);
// i is reported as 3 within a
Console.WriteLine("i = " + i.ToString());
// i still shows as 2 ****
So the question is why i changes for b and not for a ?
The delegate created for b *captures* the i variable - in other words,
it can still make changes to it, and see changes in the rest of the
method.
The delegate created for a doesn't capture any local variables -
instead, a value is passed in as a parameter (just as it would be for
any normal method). Incrementing that parameter value doesn't change
the original variable's value.
--
Jon Skeet - <sk***@pobox.com>
Web site:
http://www.pobox.com/~skeet
Blog:
http://www.msmvps.com/jon.skeet
C# in Depth:
http://csharpindepth.com