CSharp examples for Custom Type:Lambda
When you capture the iteration variable of a for loop, C# treats that variable as though it was declared outside the loop.
The same variable is captured in each iteration.
Action[] actions = new Action[3]; for (int i = 0; i < 3; i++) actions [i] = () => Console.Write (i); foreach (Action a in actions) a(); // 333
We can illustrate this better by expanding the for loop as follows:
Action[] actions = new Action[3]; int i = 0; actions[0] = () => Console.Write (i); i = 1; actions[1] = () => Console.Write (i); i = 2; actions[2] = () => Console.Write (i); i = 3; foreach (Action a in actions) a(); // 333
To write 012, assign the iteration variable to a local variable that's scoped inside the loop:
Action[] actions = new Action[3]; for (int i = 0; i < 3; i++) { int loopScopedi = i; actions [i] = () => Console.Write (loopScopedi); } foreach (Action a in actions) a(); // 012