When you capture the iteration variable of a for loop, C# treats that variable as though it was declared outside the loop. This means that the same variable is captured in each iteration. The following program writes 333 instead of writing 012:
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
actions [i] = () => Console.Write (i);
foreach (Action a in actions) a(); // 333
I'm reading C# in a Nutshell (5th Edition) and today i came across this but i can't get my head over it, i don't get why the output is 333
and not 012
. Is it because the value of i
that's getting printed is the value after the loop? How is that possible? i
is supposed to be disposed after the loop, isn't it?