Sobes.tech
Middle+

Collection of functions, loop 0-9, add lambdas capturing i, call all. What will it output?

sobes.tech AI

Answer from AI

In C#, when creating lambdas inside a loop that capture the loop variable (for example, i), all lambdas will reference the same variable i. After the loop finishes, the value of i will be 10, so when calling all lambdas, they will output 10.

Example:

var actions = new List<Action>();
for (int i = 0; i < 10; i++)
{
    actions.Add(() => Console.WriteLine(i));
}

foreach (var action in actions)
{
    action(); // will print 10 ten times
}

To get the expected output from 0 to 9, you need to capture a copy of the variable inside the loop:

for (int i = 0; i < 10; i++)
{
    int copy = i;
    actions.Add(() => Console.WriteLine(copy));
}

Then, when calling the lambdas, they will output numbers from 0 to 9.

Collection of functions, loop 0-9, add lambdas… - sobes.tech