I was browsing through some C# examples and came upon this:
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
delegate void Printer();
static void Main()
{
List<Printer> printers = new List<Printer>();
for (int i = 0; i < 10; i++)
{
printers.Add(delegate { var d = i; Console.WriteLine(d); });
}
foreach (var printer in printers)
{
printer();
}
Console.ReadLine();
}
}
}
I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.
However, this outputs 10 ten times.
Why is this? Is the int not a reference instead inside the delegate?
Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.
Edit: Example of my confusion
int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);
This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.
Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?
In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.