While experimenting with closures in C# I found out that they work rather unexpectedly if they capture an iterator variable in a loop.
var actions = new List<Action>();
foreach (int i in new[] { 1, 2 })
actions.Add(() => Console.WriteLine(i));
for (int i = 3; i <= 4; i++)
actions.Add(() => Console.WriteLine(i));
foreach (var action in actions)
action();
The above code produces a strange result (I'm using .NET 4.5 compiler):
1
2
5
5
Why is the value of i
captured differently for 2 almost identical loops?