Unity Developer Question:

Download Job Interview Questions and Answers PDF

Can you predict the output of the code below?

Unity Developer Interview Question
Unity Developer Interview Question

Answer:

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.

Download Unity Developer Interview Questions And Answers PDF

Previous QuestionNext Question
Tell us have you ever mentored anyone before? If yes, describe the situation?Tell us do you value recognition or pay more? Why?