beppe beppe - 26 days ago 10
C# Question

cannot understand lamda expression output

I have this code and do not understand why the out put is 22! I am afraid it should be 01!
can anyone explain what happens? if the list store a method with a parameter, so the parameters should be 0 and 1 respectively!

List<Action> list = new List<Action>();

for (int i = 0; i < 2; i++)
{
list.Add(() => Console.Write(i));
}

foreach (var it in list)
{
it();
}

Answer Source

It is Closure (1, 2).

In your case Console.Write(i) will use value of i in the moment of action call. You firstly increment i in for loop then in second loop you call every action in the list. In the moment of call of every action i has value 2 - so, you get 22 as output.

To get expected result you should create local copy of i and use it:

for (int i = 0; i < 2; i++)
{
    var temp = i; 
    list.Add(() => Console.Write(temp));
}