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.
Addstatement creates a method object that encapsulates the passed parameter. Why would it print "five"?foreachto capture the variable in the closure.foreach, but that variable would change with each iteration thus resulting in the lambdas all having the same value. It was changed in .Net 4.0 because that is not what you would expect.