Avatar ·

Why does a foreach loop variable get captured incorrectly by a lambda in C#?

Hi everyone! I recently started learning C# and encountered very strange behavior when using lambda expressions inside a `foreach` loop. I have simple code where I create a list of actions that should output numbers from 0 to 4: ```csharp var actions = new List(); for (int i = 0; i < 5; i++) { actions.Add(() => Console.WriteLine(i)); } foreach (var action in actions) { action(); } ``` This code outputs: 5, 5, 5, 5, 5. I understand that this is because the variable `i` is captured by reference, and by the time the lambdas are called, it is already 5. That makes sense. But when I do the same with `foreach`: ```csharp var actions = new List(); foreach (var i in Enumerable.Range(0, 5)) { actions.Add(() => Console.WriteLine(i)); } foreach (var actio