The other day I read the following two blog posts:
Eric Lippert, Closing over the loop variable considered harmful
The basic summary of these two posts is that closing over the loop variable, rather than the loop value, is a language feature in both C# and JavaScript that is confusing and can cause significant and puzzling bugs.
That in mind, I was reading some MSDN documentation today on the use of generics, and I came across some code that confuses me greatly. Here is the code:
class TestGenericList
{
static void Main()
{
// int is the type argument
GenericList<int> list = new GenericList<int>();
for (int x = 0; x < 10; x++)
{
list.AddHead(x);
}
foreach (int i in list)
{
System.Console.Write(i + " ");
}
}
}
This code bears a superficial resemblance to the code in the linked blog posts. Obviously this code outputs {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
and not {10, 10, 10, 10, 10, 10, 10, 10, 10}
. Can anyone explain to me why this code is not a closure?