I have the following code snippet in C#:
var actions = new List<Func<int>>();
IEnumerable<int> values = new List<int> { 1, 2, 3 };
foreach (int value in values)
{
actions.Add(() => value * value);
}
foreach (var action in actions)
{
Console.WriteLine(action()); ;
}
Console.ReadLine();
It's running fine, but I am not getting the result I expect.
Actual result
9,9,9
Expected result
1,4,9
Why am I not getting the result I expect?
You're capturing the loop variable within your lambda expression, which means when the delegate is finally invoked, it's seeing the final value of the loop variable.
Simple fix:
This way you get a new
copy
variable in each iteration of the loop, so each delegate expression will capture a different variable, and they're not affected by the loop variable (value
) changing over time.Eric Lippert explains this well in "Closing over the loop variable considered harmful" (and part two).
Basically this is a "gotcha" in C# which nearly everyone falls for sooner or later.
You need to capture the variable inside the loop. Right now your delayed execution actions are using the last value of
value
from the firstforeach
loop.Note the
var v = value;
line.