captured-variable

C# Captured Variable In Loop

I met a interesting issue about C#. I have code like below List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 5) { actions.Add(() => variable * 2); ++ variable; } foreach (var act in actions) { Console.WriteLine(act.Invoke()); } I expect it to output 0, 2, 4, 6, 8. However, it actually o...

Captured variable instantiating problem

I'm currently musing about some idea I can't get right. The problem is that I want to use one lambda function to instantiate a captured variable and another lambda to access a property of that variable. Since the instantiating happens within the lambda the variable isn't actually instantiated the time I want to use it within the second...