Answers

Question and Answer:

  Home  Unity Developer

⟩ Can you predict the output of the code below?

delegate void Iterator();

static void Main()

{

List iterators = new List();

For (int i = 0; i < 15; i++)

{

iterators.Add(delegate { Console.WriteLine(i); });

}

Foreach (var iterator in iterators)

{

iterator();

}

}

This program tests the prospective developer on their experience working with loops and delegates. At first glance, one would expect the program to output the numbers 0 to 15, fifteen times. Instead, the number 15 is printed fifteen times. Since the delegate is being added within the for loop, and because the delegate is only referencing the variable i instead of the value itself, the loop sets the value of the variable i to 15 before it is invoked within each delegate.

 135 views

More Questions for you: