In this answer https://mcmap.net/q/35777/-is-quot-access-to-modified-closure-quot-resolved-by-comprehension-syntax Eric Lippert says that "FYI we are highly likely to fix this in the next version of C#; this is a major pain point for developers" with regards to how the foreach loops uses the variable.
In the next version each time you run through the "foreach" loop we will generate a new loop variable rather than closing over the same variable every time. This is a "breaking" change but in the vast majority of cases the "break" will be fixing rather than causing bugs.
I have not been able to find anything indicating that this change has been made yet. Is there any indication that this is how the foreach loop will work in C# 5?
foreach
that is being referred to is a C# language feature, not a .NET Framework feature. – Nordinforeach
variable is an "inside" variable, and a different "copy" is captured in each iteration). Have you actually verified that changing the language version works, for you? (This is mostly of theoretical interest; I don't think anyone would want the C# 4 behavior in practice). – Tarrsus