Why does this example gives me ten times 10?
namespace ConsoleApp
{
internal class Program
{
delegate void Printer();
static void Main(string[] args)
{
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();
}
}
}
}
I expected it to throw an exception because i
don't exist outside the loop.
I read a question on this forum with a similar topic and they mentioned how the scope and lifetime of the variable differ, but I'm still not sure what does that exactly mean.
Does i
hold some kind of reference count and wait for it to become 0?