How do you capture iteration variables?

.net, c#, for-loop, lambda

Solution

The variable `i` is captured inside the `for` loop but your are kind of extending the scope of it by doing so. So the variable is left at it's last state which was 3, hence the code outputting 333.

Another way to write the code is this:

Action[] actions = new Action[3];
int i; //declare i here instead of in the for loop

for (i = 0; i < 3; i++)
    actions [i] = () => Console.Write (i);

//Now i=3
foreach (Action a in actions) a(); // 333

The output is the same as writing:

Console.Write(i);
Console.Write(i);
Console.Write(i);

Problem

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?

Original source

Related problems