Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0196 lambda and iteration variables

using System; class Program { public static void Main() { Action[] actions = new Action[3]; for (int i = 0; i < 3; i++) { actions[i] = () => Console.WriteLine(i); } for (int i = 0; i < 3; i++) { actions[i](); } } } The output: 3 3 3 The fix the problem: using System; class Program { public static void Main() { 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; for (i = 0; i < 3; i++) { actions[i](); } } } The output: 012