I've noticed the following. This C# code:
List<Action> methodList = new List<Action>();
for (int iFn = 0; iFn < 4; ++iFn)
{
void thisLocalFunction()
{
string output = iFn.ToString();
Console.WriteLine(output);
}
methodList.Add(thisLocalFunction);
}
for (int iFn = 0; iFn < methodList.Count; ++iFn)
{
methodList[iFn]();
}
Produces 4, 4, 4, 4. On the other hand, this code:
List<Action> methodList = new List<Action>();
for (int iFn = 0; iFn < 4; ++iFn)
{
string output = iFn.ToString();
void thisLocalFunction()
{
Console.WriteLine(output);
}
methodList.Add(thisLocalFunction);
}
for (int iFn = 0; iFn < methodList.Count; ++iFn)
{
methodList[iFn]();
}
Produces 0, 1, 2, 3.
I'm not sure I understand why. I've read a bit about "capturing" but I'm not sure if that's related to what's going on here. Could someone give me a breakdown of why the two implementations behave differently?