The code snippet below will output the number '10' ten 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();
}
}
This is because (taken from https://www.toptal.com/c-sharp/interview-questions#iquestion-90455):
"the delegate is added in the for loop and “reference” to i is stored, rather than the value itself. Therefore, after we exit the loop, the variable i has been set to 10, so by the time each delegate is invoked, the value passed to all of them is 10."
My question is: Why is "reference" to i is stored?