1

Could any one explain what is going on in the below code? Why is nothing getting printed?

var actions = new Action[100];
for(int i=0;i<100;i++)
{
    actions[i] = () => DoSomething(i);
}

foreach(var action in actions)
{
    action();
}

void DoSomething(int i)
{
    if(i % 9 == 0)
        Console.WriteLine("{0} is a multiple of 9",i);
}
tichra
  • 557
  • 5
  • 18

1 Answers1

10

Classical Closure and captured variables problem. Change your loop as

 for(int i=0;i<100;i++)
 {
     int j = i;
     actions[i] = () => DoSomething(j);
 }

For more info: http://csharpindepth.com/articles/chapter5/closures.aspx

Eser
  • 12,346
  • 1
  • 22
  • 32