What is printed by: var acts = new List(); for (int i = 0; i < 3; i++) acts.Add(() => Console.Write(i)); foreach (var a in acts) a();?
Correct answer D. 333
Explanation
A lambda captures variables, not values. The for loop declares a single variable i shared by all iterations, so all three lambdas refer to it. By the time they run, the loop has finished and i is 3, so each prints 3. A foreach loop variable is fresh per iteration since C# 5, and copying i into a local inside the loop also gives 012.
Answer checked How we write and check questions
Discussion