0

I found this in toptal.com. how come output of this is ten 10 times?

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 (var printer in printers)
      {
           printer();
      }
}
aspxsushil
  • 514
  • 1
  • 5
  • 16
  • 2
    Because the for-loop is adding 10 delegates with `console.writeline` which are executed afterwards inside the `foreach`. – C4d Feb 27 '17 at 07:47
  • 1
    Use *local variable*: `for (int i = 0; i < 10; i++) { int x = i; printers.Add(delegate { Console.WriteLine(x); }); }` – Dmitry Bychenko Feb 27 '17 at 07:50
  • @DmitryBychenko using a foreach loop over an `Enumerable.Range(0, 10)` would work too, would it not? – overactor Feb 27 '17 at 07:54
  • Okay. the idea was variable capturing. got it. :). https://blogs.msdn.microsoft.com/matt/2008/03/01/understanding-variable-capturing-in-c/ helped – aspxsushil Feb 27 '17 at 08:03
  • @overactor: Linq is *lazy* (unless it's not *materialized*), so the query is perfomed at `foreach` and this will, probably, work too. However, *Linq* has its own traps, please, provide the code snippet for details. – Dmitry Bychenko Feb 27 '17 at 08:22

0 Answers0