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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With