I stumbled across this article and found it very interesting, so I ran some tests on my own:
Test One:
List actions = new
Yes.
In Test One the var i
is captured in the loop, but i
refers to a variable that is effectively declared once outside the loop, so all of the captured lambdas refer to the one variable. By the time you call the actions the value of i
is 5
so all of the output is five.
In Test Two the var j
is captured in the loop, but in this case j
is declared each time inside the loop, so all of the captured lambdas refer to the distinct variables. So calling the lambdas outputs the distinct values.