Apologies if this question has been asked already, but suppose we have this code (I\'ve run it with Mono 2.10.2 and compiled with gmcs
2.10.2.0):
The following happens in loop 1 and 3:
The current value is assigned to the variable str
. It is always the same variable, just with a different value in each iteration. This variable is captured by the lambda. As the lambda is executed after the loop finishes, it has the value of the last element in your array.
The following happens in loop 2:
The current value is assigned to a new variable localStr
. It is always a new variable that gets the value assigned. This new variable is captured by the lambda. Because the next iteration of the loop creates a new variable, the value of the captured variable is not changed and because of that it outputs "foo".