Practice mode C#

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.