1

When I add to array of Actions with a for loop a delegate the I is updated across the array. How to prevent that from happening?

I have tried assigning the "I" to an integer before adding that works.

Action[] actions = new Action[100];

for (int i = 0;i< actions.Length; i++)
{
    actions[i] = () => Console.WriteLine("Hello"+ i);
}

"I" in each Action in Action[] is 100;

Why is that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user18984
  • 57
  • 1
  • 9
  • 2
    Possible duplicate of [How to tell a lambda function to capture a copy instead of a reference in C#?](https://stackoverflow.com/questions/451779/how-to-tell-a-lambda-function-to-capture-a-copy-instead-of-a-reference-in-c) – adjan Apr 12 '19 at 09:09

2 Answers2

0

Here and Here are good explanations on similar question. Here is also good explanation on C# closures by Jon Skeet.

In for loop there is only one single variable i used. That's why later on when you are executing actions, they all reference to same value i=100. If action need to use actual value of the current i you have to capture a copy of it and store copy to action.

for (int i = 0;i< actions.Length; i++)
{   
    int copy = i;
    actions[i] = () => Console.WriteLine("Hello"+ copy);
}
Risto M
  • 2,919
  • 1
  • 14
  • 27
0

because they are all assigned to the same local variable "int i" and after the loop end "i" is 100

Action[] actions = new Action[100];

for (int i = 0;i< actions.Length; i++)
{
    int a = i;
    actions[i] = () => Console.WriteLine("Hello"+ a);
}

after declare int a = i , you have respective a for each actions

Kuei
  • 1
  • 1