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 output five 10s.
It seems that it is due to all actions are referring to one captured variable. As a result, when they get invoked, they all have same output.
Is there any way to walk round this limit to have each action instance have its own captured variable?