Explanation on closures

S

sjoshi23

Hi All

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<int> a = 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 ?

thanks
Sunit
 
J

Jon Skeet [C# MVP]

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<int> a = 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top