Using .net 4.0, why does the following code print out 'one, two, three, four, five' rather than just printing out 'five' every time?
public void Go()
{
List<Action> printActions = new List<Action>();
String[] strings = new[] {"one", "two", "three", "four", "five"};
foreach (String s in strings)
printActions.Add(() => Console.WriteLine(s));
foreach (Action printAction in printActions)
printAction();
}
As far as I can tell, using older versions of .net, i should be running into the problem addressed here (using foreach variable in a closure), but in this case, the code appears to work.