From the book C# in Depth
static void Main()
{
// First build a list of actions
List<Action> actions = new List<Action>();
for (int counter = 0; counter < 10; counter++)
{
actions.Add(() => Console.WriteLine(counter));
}
// Then execute them
foreach (Action action in actions)
{
action();
}
}
this will print 10 10 10...
static void Main()
{
// First build a list of actions
List<Action> actions = new List<Action>();
for (int counter = 0; counter < 10; counter++)
{
int copy = counter;
actions.Add(() => Console.WriteLine(copy));
}
// Then execute them
foreach (Action action in actions)
{
action();
}
}
this will print 10 9 8 ..
I dont understand why