Avatar ·

Why is the foreach loop variable captured by reference in a lambda expression in C#?

Hi everyone! I'm a beginner C# developer and I encountered very strange behavior when using foreach with lambda expressions.\n\nI have this code:\n\n```csharp\nvar actions = new List();\nvar numbers = new List { 1, 2, 3, 4, 5 };\n\nforeach (var number in numbers)\n{\n actions.Add(() => Console.WriteLine(number));\n}\n\nforeach (var action in actions)\n{\n action();\n}\n```\n\nI expected the console to output:\n\n```\n1\n2\n3\n4\n5\n```\n\nBut instead I see:\n\n```\n5\n5\n5\n5\n5\n```\n\nWhy does this happen? I read that it's related to how C# handles the loop variable in foreach. But I don't understand why it behaves as the "same" variable on each iteration instead of being created anew. In a for loop, as far as I know, everything works differently.