Closing over the loop variable, part two

Closing over the loop variable, part two

Rate This
  • Comments 51


UPDATE: We are taking the breaking change. In C# 5, the loop variable of a foreach will be logically inside the loop, and therefore closures will close over a fresh copy of the variable each time. The "for" loop will not be changed. We return you now to our original article.

Thanks to everyone who left thoughtful and insightful comments on last week's post.

More countries really ought to implement Instant Runoff Voting; it would certainly appeal to the geek crowd. Many people left complex opinions of the form "I'd prefer to make the change, but if you can't do that then make it a warning". Or "don't make the change, do make it a warning", and so on. But what I can deduce from reading the comments is that there is a general lack of consensus on what the right thing to do here is. In fact, I just did a quick tally:

Commenters who expressed support for a warning: 26
Commenters who expressed the sentiment "it's better to not make the change": 24
Commenters who expressed the sentiment "it's better to make the change": 25

Wow. I guess we'll flip a coin. :-)    (*)

Four people suggested to actually make it an error to do this. That's a pretty big breaking change, particularly since we would be breaking not just "already broken" code, but plenty of code that works perfectly well today -- see below. That's not likely to happen.

People also left a number of interesting suggestions. I thought I'd discuss some of those a little bit.



foreach(var x in c) inner
foreachnew(var x in c)
foreach(new var x in c)
foreach(var x from c)
foreach(var x inside c)




[q, &r] (int x) -> int { return M(x, q, r); }

This means that the lambda captures outer variable q by value, captures r by reference, takes an int and returns an int. Whether the lambda captures values or references is controllable! An interesting approach but one that doesn't immediately solve our problem here; we cannot make lambdas capture by value by default without a huge breaking change. Capturing by value would have to require new syntax, and then we're in the same boat again: the user has to know to use the new syntax when in a foreach loop.

A number of people also asked what the down sides of adding a warning are. The down side is that a warning which warns about correct behaviour is a very bad warning; it makes people change working code, and frequently they break working code in order to eliminate a warning that shouldn't have been present in the first place. Consider:

foreach(var insect in insects)

This makes a lambda closed over insect; the lambda never escapes the loop, so there's no problem here. But the compiler doesn't know that. The compiler sees that the lambda is being passed to a method called Where, and Where is allowed to do anything with that delegate, including storing it away to be called later. Which is exactly what Where does! Where stores away the lambda into a monad that represents the execution of the query. The fact that the query object doesn't survive the loop is what keeps this safe. But how is the compiler supposed to suss out that tortuous chain of reasoning? We'd have to give a warning for this case, even though it is perfectly safe.

It gets worse. A lot of people are required by their organizations to compile with "warnings are errors" turned on. Therefore, any time we introduce a new warning for a pattern that is often actually safe and frequently used, we are effectively causing an enormous breaking change. A vaccine which kills more healthy people than the disease would have is probably not a good bet. (**)



And finally, a number of people made suggestions of the form "make it a warning in C# 4, and an error in C# 5", or some such thing. FYI, C# 4 is DONE. We are only making a few last-minute "user is electrocuted"-grade bug fixes, mostly based on your excellent feedback from the betas. (If you have bug reports from the beta, please keep sending them, but odds are good they won't get fixed for the initial release.) We are certainly not capable of introducing any sort of major design change or new feature at this point. And we try to not introduce semantic changes or new features in service packs. We're going to have to live with this problem for at least another cycle, unfortunately.


(*) Mr. Smiley Face indicates that Eric is indulging in humourous japery.




  • @Michael Greger and @AC - I can't think of a good scenario where someone would deliberately rely on the current foreach closure behavior, but as a few people have pointed out: a real problem that would come into play if the breaking change was made in a future C# version is "multi targeting bugs."

    As Pop.Catalin put it:  "code written with the new foreach rules will not work correctly when re targeted to older compilers (C# 2.0, C# 3.0, C#4.0)"  The pains and problems would continue to live on indefinitely into the future, and now the problem would be that developers who understand and rely on the new foreach closure behavior and are required to have their libraries available in older versions would get bitten.

  • I was thinking about the C++ approach you mentioned:


    and what would be a C#-esque way to express that concept. Obviously as you point out it doesn't solve the problem for foreach at all, but it still seems like an interesting and useful feature if the syntax can be made less opaque. (Of course, that's not a problem for C++ because "the syntax shouldn't be opaque" seems to be an explict design-NON-goal... that fragment is positively transparent by C++ standards! ;) )

    Here's what I came up with that would be Csharpey...

    x => {

     var q;

     ref r;

     return M(x, q, r);


    The "ref r" might be redundant since capture-by-reference is the default behavior, but maybe not, because you could require that if there are *any* explicit declarations of what is being captured, then *all* variables being captured must be explicitly so declared, to avoid accidental introduction of something that captures. Since neither "var q;" nor "ref r;" are legal statements in C# today*, I don't think that's a breaking change. It'd be nice to have a way to specifically declare that nothing should be captured, too, but I'm not sure what that'd be, there's not an obvious extension of this syntax for it.

    * with the caveat that all the necessary hoops for the case where a real type called "var" is in scope have already been jumped through.

  • @Stuart - I think the C++ syntax is fine for C#, just replace the & with ref:

    [q, ref r] x => M(x, q, r)

    It would also be nice to have a compiler setting that would force all captured variables to be explicitly declared in this manner.  This could help beginner developers and also avoid the foreach problem.

  • I've run into the same issues Daniel Earwicker did. We use and like ReSharper, but finally changed "Access to modified closure" to a hint rather than a warning. The majority of the time the query object doesn't survive the loop. And if it does, hopefully the developer wrote a unit test. :)

  • @DrBlaise, I agree with what you're saying in theory, but in practice, why can't this simple change be back propagated to the old 2.0 compilers as well?

    No, that makes things even worse. Then you end up with two nigh-indistinguishable compilers that produce different results for the same program text. -- Eric

    Isn't it better to fix an issue and take some pain over propagating it forever?

    Sometimes it is, sometimes it isn't. If it were an easy choice with a bright line then we wouldn't be having this conversation. -- Eric

    I take back my 'no warnings' stance and think it should at least be a warning. For the people who never read warnings (most of the people I work with) it's no big deal. They write horrendous and buggy code regardless. For the errors-as-warnings crowd, they won't mind a little explicitness or the odd #pragma ignore.

    I assure you from long and painful experience OH YES THEY WILL. Case in point: A couple years ago I noticed that there are some obscure cases where we do not report a "variable was never used", or "variable was written but never read" warning when we possibly could. So I added it to an internal-only build of the compiler. OH THE PAIN. Suddenly thousands of people, all of whom had "warnings as errors" turned on by default, were getting their builds broken because the compiler was now correctly pointing out that a particular variable in their program was never used.

    But, they all loudly pointed out to me, the variables in question were being read via private reflection, or via some unsafe interop scenario, or via code spit into an expression tree or blah blah blah blah blah -- some mechanism that was extraneous to the language and therefore not detectable by the compiler. Would I please turn off the damn warning, no we do not care if the warning is correct and consistent with every other "variable not used" warning, it is breaking us now, we're trying to ship a product here, get rid of it.

    Imagine what would happen had we allowed to get that out into the wild. It wouldn't just be a few thousand people at Microsoft vexed with me, I tell you what.

    Adding warnings is often a HUGE breaking change. We really don't want to do it unless we are sure that doing so is not worse than simply living with the bad-smelling behaviour that the warning would be detecting.

    -- Eric

  • > For the errors-as-warnings crowd, they won't mind a little explicitness

    I, for one, would definitely mind any warning over a _correct_ (i.e. non-escaping) use of an iteration variable in a lambda, or any construct which introduces lambdas under the hood (such as LINQ comprehensions).

  • It's great that you're taking this problem so seriously. I moved to C# from C++ partly because of the insane amount of this type of baggage in C++.

    In my mind, where the scoping of variables is not immediately obvious (e.g. foreach, query expression syntax), capturing variables by reference is dangerous and should not be the default.

    I know you hate syntactic baggage, but how about a new way of declaring a lambda that defaults to capturing by value. For example, x -> foo(x, y). Additional annotation, similar to the C++, could then allow by reference.

  • I have been following this thread. This is great thread that touches many aspects in the software development cycle.

    I have asked this question when the “var” is introduced to the “foreach” loop: Computer is used to eliminate repeated tasks, why we need the "var" in the “foreach (var item in items). After following the thread, I see the good usage of the “var” in the “foreach”.

    I agree with Pavel. This is a bug. “Foreach var” is clear enough to demand a new object in items.

    Historically, Microsoft has resolved a similar issue in C++ a few years back. The issue is in our buddy “for” loop too.

    In the older c/c++ compilers (before VC6?), the following “i” can be used outside the “for” loop.



               Do something with i


            fprint(i);  // ok

    However ANSI C++ does not allow the "i" can be referenced out side the "for" loop. In order to compile with ANSI C++ and to keep the backward compatible, the new VC compiler has a compiler flag /Ze for the people who want to keep the above code works.

    I think we can do the same for the foreach issue. Add a check box in the Build tab in the project setting for the people want the old behavior.


    I don't buy the "people are screaming so we can't do it" argument. The people who disagree will always scream, but that doesn't make them right. Yes, some people will have their builds broken; that's the WHOLE POINT of building with warnings-as-errors, to aggressively find bugs before they reach users. Those people usually understand that the potential for false positives is the unavoidable result of not having an omniscient compiler; but they are willing to pay that price in order to produce a higher quality product. I am sure there were some people who unreasonably insisted that they should be able to have their cake and eat it too: compile with warnings-as-errors AND never have their build break. But imagine how many more people, both immediately and in the future, would be able to find bugs that would have otherwise gone undetected? Why should they suffer because some people who chose to build with warnings-as-errors don't like the fact that they can't lazily upgrade from one version to the next?

  • Hi, I made the confusing comment before. I had been under the impression that C# closures were dynamic, not lexical, because of this issue and other results from modifying a variable after closing over it. It appears that I was wrong - Pavel's comment after mine straightened me out about how a call to a closure in a different scope refers to the old scope. I was under the impression that lexical closures acted by closing over the value in the current scope.


    That compiler option in VC++ has caused untold grief in and of itself, because for a certain time period (roughtly until VC++2005 became common), you never knew if a piece of C++ code you've got from somewhere expected to have it turned on or off. It effectively amounts to sneaking in a second, incompatible, dialect of the same language. As a result, many people resorted to a "#define for hack" to force reduced scope regardless of compiler settings:

       #define for \

           if(false); else

    In the scenario we're discussing, the effect of doing the same thing would be even worse, because here the incompatible dialect is _quietly_ incompatible - a program compiled with a wrong setting will compile successfully, it just won't do the right thing - and there's no guarantee that "wrong thing" would be an exception and not, say, incorrectly computed result leading to unrecoverable data corruption (when said result is used to update some existing data).

    There is a different take on this, though... I do wish sometimes for more languages, C# included, to provide some form of explicit versioning mechanism, guaranteed to be forward-compatible, that can then be used to select the correct behavior when a breaking change, or a quiet semantics change, is introduced in a new version of the language (which permits such changes to be introduced more often to begin with). For example, in XQuery, a module can start with a version declaration:

       xquery version "1.0";

    and the language spec requires the implementation to only accept a version declaration if it can support the precise semantics mandated by a spec for that version (it can be less restrictive by adding extensions, but it cannot change the meaning of code, or refuse to compile it, if it's valid for the version specified).

    This allowed them to introduce breaking changes. For example, in XQuery 1.0, "function" isn't a keyword in expression context, and so this:


    is interpreted as a call to a function named "function", passing the value of variable $x as an argument. In XQuery 1.1, "function" in expression context is a keyword that starts a lambda expression, so the above code would parse it as such, $x as lambda parameter declaration, and then expect { to follow the ) to mark the beginning of lambda body.

    An XQuery implementation can only support 1.1 and refuse 1.0, or support 1.0 and refuse 1.1, or support both; and if I write my code relying on presence or absence of such features (or, in general, when writing any code, assuming future breaking changes), I can mark it with a version declaration, and know that, no matter what, it will either work precisely the way I expected it to do according to the spec, or fail to run if the exact meaning I relied on is not supported by the implementation.

  • My £0.01206: (= $0.02)

    Introducing a new syntax is a bad idea. You would either have a new syntax for the new behaviour, which would not be particularly discoverable and would likely remain unused, or a new syntax for the old behaviour, in which case you might as well just make the change and let anyone who needs the old behaviour use a workaround.

    A warning would be nice if it was 100% accurate, but that sounds infeasible. An information message would also need to be 100% accurate to be of any use. If it's not accurate, it would become the Visual Studio equivalent of the "Are you sure you want to run this virus and let gangsters pwn your data?" dialogs that so many users read as "Click Yes to close this annoying message-thingy and get on with what you were trying to do (probably viewing naughty pictures)".

    Changing the implementation will *probably* not break any code, and certainly looks like the best option, but there are plenty of other changes to the framework which have been rejected because they *might* break code.

    Eg: ColorTranslator.FromHtml throws a System.Exception

    "We cannot make assumptions about programming practices and therefore we cannot change an outer exception in case deployed application are catching that specific exception."

    Maybe for .NET 5 you should throw caution to the wind, ignore backwards-compatibility, fix any language issues like this, and completely refactor the BCL. You could get rid of any hang-overs from v1, such as non-generic collections; you could move the ExtensionAttribute to mscorlib to allow extension methods anywhere in the framework; you could split System.Web so that MVC apps don't get a reference to WebForms controls; you could remove some of the duplication between WPF and WinForms.

    Perhaps v5 is optimistic, but if you don't do something before v10, I fear the framework may become bloated with backwards-compatibility junk, and end up being the VB6 of 2025.

  • About refactoring the BCL in .net 5 i totally agree, .NET has evolved very fast and went from sub part to on par to more advanced than most platforms in very little time. I don't think the people still using non generic collections are the ones who are likely to dig into lamda and dynamic so i think it would be nice to say , for .NET 5, ".NET 4 and before is legacy and maintained for the next 3 years , .NET 5 removes everything that has been made obsolete by newer frameworks". This would be an opportunity to remove a lot of bloat and , if it aint there , newcommers don't risk using it.

  • A better analogy than "A vaccine which kills more healthy people than the disease would have is probably not a good bet" might be "Medicine which kills more people than the disease it's supposed to cure is not a good bet".  

    Of course, analogies are like feathers on a snake.

  • A late vote for fixing the foreach statement. The design was a mistake; it's by far the biggest wart in the language - and if it would do virtually no harm to fix, then please fix it if you can!

    When I first made this error, I was dismayed. Every time I write

    var temp = it; // don't remove this line

    I'm still dismayed.

    Conversely, I can't think of a reason anyone would be depending on the current semantics. A look though the comments from your clever readers was, unusually, completely unilluminating.

    Did I miss an example of a reasonable use of the current semantics that the change would break? (For some reasonable interpretation of 'reasonable'?)

    Ta, Pete.

Page 3 of 4 (51 items) 1234