Why is this output 333 not 0112 in Array.ForEach?

Why is the code below not 333 not 012? I think the code is so simple, and I check and check and double check, triple check, until I can get an answer. Can anybody help me?

Action[] tmp = new Action[3];

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

Array.ForEach(tmp, m => m());

Console.Read();
+4
source share
2 answers

You must change your code to:

Action[] tmp = new Action[3];

for (int i = 0; i < tmp.Length; i++)
{
    int j = i;
    tmp[i] = () => Console.WriteLine(j);
}

Array.ForEach(tmp, m => m());

Console.Read();

The reason is closing the nest

See the following links for more details: Is there a reason for reusing a C # variable in foreach? http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/

+1
source

, i, for " ", ! , (i) (3), .

, ( , , "- " ):

for (int _i = 0; _i < tmp.Length; _i++)
{
    int i = _i; // NEW/fresh variable, i, introduced each loop
    tmp[i] = () => Console.WriteLine(i);
}

( ) # foreach? - for foreach "" # 4 , "" foreach # 5.

, . "gotchas" #, , . # 5 foreach , . -

+1

Source: https://habr.com/ru/post/1539079/


All Articles