I encountered this strange behavior with captured variables. Below are two loops. I would expect both to behave the same. Why it behaves differently?
private static void Loop1()
{
var actions = new List<Action>();
foreach (var number in Enumerable.Range(1, 5))
{
actions.Add(()=>Console.WriteLine(number));
}
foreach (var currentAction in actions)
{
currentAction();
}
}
private static void Loop2()
{
var actions = new List<Action>();
for (int number = 0; number <= 4; number++)
{
actions.Add(() => Console.WriteLine(number));
}
foreach (var currentAction in actions)
{
currentAction();
}
}
The first loops print 1,2,3,4,5 The second loop prints 5,5,5,5,5