Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this for iteration variable still around after the for loop?

Tags:

c#

I have been reading some C# interview questions and found a permutation of a popular one about delegates the code of which puzzles me.

The question was:

Predict the output of the code below.

delegate void Iterator();

static void Main(string[] args)
{
    List<Iterator> iterators = new List<Iterator>();
    for (int i = 0; i < 15; i++)
    {
        iterators.Add(delegate { Console.WriteLine(i); });
    }

    foreach (var iterator in iterators)
    {
        iterator();
    }

    Console.Read();
}

The normal version of this question I've seen declares the i variable before the for loop, thus making it method-wide and from there it's easy to see why the output is "15" 15 times.

However when I debugged the code the i variable is out of scope in the foreach loop and does not exist, anymore. Yet, when I step into the iterator() method it exists for the Console.WriteLine(i) line.

This I cannot understand.

like image 998
J. Doe Avatar asked Dec 29 '18 21:12

J. Doe


1 Answers

The compiler translates your code to the following code, this is why i variable is not out of scope.

private delegate void Iterator();

[CompilerGenerated]
private sealed class CompGenCls
{
    public int i;

    internal void CompGenFunc()
    {
        Console.WriteLine(i);
    }
}

private static void Main(string[] args)
{
    List<Iterator> iterators = new List<Iterator>();
    CompGenCls obj = new CompGenCls();
    obj.i = 0;
    for (; obj.i < 15; obj.i++)
    {
        iterators.Add(obj.CompGenFunc);
    }

    foreach (Iterator item in iterators)
    {
        item();
    }
    Console.Read();
}
like image 109
Ahmad Ibrahim Avatar answered Oct 31 '22 16:10

Ahmad Ibrahim