Skip to content

Print, print, print...

Akkiraju Ivaturi

Akkiraju Ivaturi

Asked Sep 7, 2012, 7:22 PM EDT1 answer
Share
LinkedInX

Here's some code using the anonymous method feature of C# 2. What does it do?


using System;
using System.Collections.Generic;

class Test
{
delegate void Printer();

static void Main()
{
List<Printer> printers = new List<Printer>();
for (int i=0; i < 10; i++)
{
printers.Add(delegate { Console.WriteLine(i); });
}

foreach (Printer printer in printers)
{
printer();
}
}

}  

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Akkiraju Ivaturi
    0
    There's only one i variable here, and its value changes on each iteration of the loop. The anonymous methods capture the variable itself rather than its value at the point of creation - so the result is 10 printed ten times!  
    0