Partager via


Closing over the loop variable, part two

(This is part two of a two-part series on the loop-variable-closure problem. Part one is here.)


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.

First off, I want to emphasize that what we're attempting to address here is the problem that the language encourages people to write code that has different semantics than they think it has. The problem is NOT that the language has no way to express the desired semantics; clearly it does. Just introduce a new variable explicitly into the loop.

A number of suggestions were for ways that the language could more elegantly express that notion. Some of the suggestions:

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)

Though we could do any of those, none of them by themselves solve the problem at hand. Today, you have to know to use a particular pattern with foreach to get the semantics you want: declare a variable inside the loop. With one of these changes, you still have to know to use a particular keyword to get the semantics you want, and it is still easy to accidentally do the wrong thing.

Furthermore, a change so small and so targetted at such a narrow scenario probably does not provide enough benefit to justify the large cost of creating a new syntax, particularly one which is still easily confused with an existing syntax.

C++ luminary Herb Sutter happened to be in town and was kind enough to stop by my office to describe to me how they are solving a related problem in C++. Apparently the next version of the C++ standard will include lambdas, and they're doing this:

[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)
{
var query = frogs.Where(frog=>frog.Eats(insect));
Console.WriteLine("{0} is eaten by {1} frogs.", insect, query.Count());
}

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. (**)

This is not to say that a warning is a bad idea, but that it is not the obvious slam dunk good idea that it initially appears to be.

A number of people suggested that the problem was in the training of the developers, not in the design of the language. I disagree. Obviously modern languages are complex tools that require training to use, but we are working hard to make a language where people's natural intuitions about how things work lead them to write correct code. I have myself made this error a number of times, usually in the form of writing code like the code above, and then refactoring it in such a manner that suddenly some part of it escapes the loop and the bug is introduced. It is very easy to make this mistake, even for experienced developers who thoroughly understand closure semantics. That's a flaw in the design of the language.

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.

(**) I wish to emphasize that I am 100% in favour of vaccinations for deadly infectious diseases, even vaccines that are potentially dangerous. The number of people made ill or killed by the smallpox vaccine was tiny compared to the number of people who did not contract this deadly, contagious (and now effectively extinct) disease as a result of mass vaccination. I am a strong supporter of vaccine research. I'm just making an analogy here people.

(This is part two of a two-part series on the loop-variable-closure problem. Part one is here.)

Comments

  • Anonymous
    November 16, 2009
    The comment has been removed

  • Anonymous
    November 16, 2009
    The comment has been removed

  • Anonymous
    November 16, 2009
    not really related to this post, but something I'd like to see would be a "what compiler warnings do you get for this and why?" WRT:    class Program
       {
          static void Main(string[] args)
           {
               var x = 5; // not used
               var y = (int)5; // not used
               var z = (int?)5;  // no warning ?!
           }
       }  

  • Anonymous
    November 16, 2009
    SuggestionBoxBob: I'd expect all you'd get would be three "variable is assigned but never used"s. Why, what other warnings might you get? Everything else about it is completely fine, with the possible exception of the redundant cast of y to the type that it already is - but I'm fairly sure that an unnecessary cast isn't a warning in C#. Your expectations would be wrong. You only get two warnings, on x and y. (I'll add some comments to the code.) The reason why we suppress the warning on z is kinda interesting; I blogged about this a couple years ago. http://blogs.msdn.com/ericlippert/archive/2007/04/23/write-only-variables-considered-harmful-or-beneficial.aspx  We suppress a "not used" warning on a local if a non-constant value is written to it. The compiler interprets (int?)5 as "new Nullable<int>(5)", which it sees as a non-constant computation which you might want to examine in the debugger.   -- Eric

  • Anonymous
    November 16, 2009
    > Though we could do any of those, none of them by themselves solve the problem at hand. Today, you have to know to use a particular pattern with foreach to get the semantics you want: declare a variable inside the loop. With one of these changes, you still have to know to use a particular keyword to get the semantics you want, and it is still easy to accidentally do the wrong thing. Eric, what about two suggestions combined (I believe I mentioned it in one of the comments)?

  1. Add a new foreach syntax for new semantics - doesn't really matter which one.
  2. Give a warning (or maybe even error) for old semantics. That way, one cannot accidentally do the wrong thing, because the compiler will complain. And yet it is also not a silent breaking change - at least if someone's code is actually intentionally relying on existing behavior (which I find extremely unlikely), they'll get a clear error message telling them what's wrong, and, ideally, how to make it right.
  • Anonymous
    November 16, 2009
    The comment has been removed
  • Anonymous
    November 16, 2009
    The comment has been removed
  • Anonymous
    November 16, 2009
    The comment has been removed
  • Anonymous
    November 16, 2009
    OK, to allow fixing the issue in C#5, I change my vote and support Pavel:
  1. Add new syntax "foreach (new var x in c)" for new semantics (inside expansion).  The keyword new gives the best hint about the difference between the two fkavours.
  2. Give a warning for old syntax and semantics (outside expansion). This avoids the breaking change. Wrong code can be found. Correct code will have to use "#pragma warning" to get rid of the warning.
  • Anonymous
    November 16, 2009
    The comment has been removed

  • Anonymous
    November 16, 2009
    The comment has been removed

  • Anonymous
    November 16, 2009
    "...a warning which warns about correct behaviour is..." An FxCop rule. :) Seriously, this is the sort of case FxCop handles really well. So one option would be to catch it with FxCop instead of the compiler. Advantage is that you can do it today. Disadvantage is that most people who would be helped by this probably don't run FxCop.

  • Anonymous
    November 16, 2009
    @Craig: FXCop can't catch that, because it analyzes compiled code, not source code. It is possible to detect such a pattern in compiled code, but given what lambdas extract to in IL, I would be surprised if FXCop is smart enough in its present state to handle that kind of thing. StyleCop could catch it, though.

  • Anonymous
    November 16, 2009
    The comment has been removed

  • Anonymous
    November 16, 2009
    The comment has been removed

  • Anonymous
    November 16, 2009
    A new foreach syntax  for this very particular case would be overkill, as would be a warning. The interaction of foreach and closures probably should have been defined differently, but now it is too late to bother fixing it. After all, no language can evolve as much as C# did since 1.0 without having some awkward legacy issues. Just keep a note for the future designers of whatever language will come after C#. And it's not only the languages that have this kind of problems, e.g. still occasionally having to use pre-generics System collections brings me on the verge of tears.

  • Anonymous
    November 16, 2009
    (Started to think about it, wild guesses) If I were to change language for two enumeration styles (I'm not yet sure if it should be done), I'd go with the syntax: for(var i in list) // i is same variable for all loop iterations foreach(var i in list) // i is new variable for each iteration If foreach body is not "pure" enough (subject to define), warning could be issued. This warning could easily be fixed by converting it to "for" loop, if needed.  Seems like there are some opportunities for "foreach" parallelization, also.  

  • Anonymous
    November 16, 2009
    Andre: I have a simpler solution. A "three sided coin". Since that is geometrically improbable, I'll do you one better - a cube, with two sides for each possible outcome. Why do programmers always try to reinvent the wheel?

  • Anonymous
    November 16, 2009
    Thinking about purity of foreach block, that could be defined as "block is pure, if extracting it as separate method of the void ExtractedBlock(iterationVariable) form is pure". Then we get that problem of checking if call to Where, Select and any other method getting delegate is pure. It can be defined with some form of PureAttribute, when it means "I'm pure if this and that parameter's body is pure". Delegate body is again subject to the transformation above, like if it can be replaced with extracted pure method, than it is pure. If by chance it is using method group, than method it resolves to should be [Pure] already. Again, those are just some ideas. Discussion is welcome!

  • Anonymous
    November 16, 2009
    I love that in todays world you have to qualify that vaccination statement.

  • Anonymous
    November 16, 2009
    @Eric "we'll Rock-Paper-Scissors for it. First you and the other side have a round, and then I'll play the winner." Japery, indeed.  Guess it was a good vacation. I say we settle the choice by havting you think of a double between 0+ and 0-, and we'll try to approximate it.

  • Anonymous
    November 16, 2009
    The comment has been removed

  • Anonymous
    November 16, 2009
    Eric, Correct me if I'm wrong, but if I understand you correctly, you give some very good arguments against making it a warning, and you basically reject the make-it-an-error option. You also repeat some argumentss against leaving the language as it is. Does that mean that you're on the let's-make-the-change side? After reading this post, I certainly repeat my "make the change" vote.

  • Anonymous
    November 16, 2009
    I said in the last post that you should at least make it a warning. I changed my mind. On many occasions I use the results of a LINQ query with the iteration variable right away, just like in the example you provided, and in those cases the warning message makes no sense. There's only one option left: make the change you suggested.

  • Anonymous
    November 16, 2009
    Make using lambdas in foreach loops illegal. That would solve the problems for sure. No closures - no problem.

  • Anonymous
    November 17, 2009
    "...a warning which warns about correct behaviour is a very bad warning;" Static code analysis tools, like Lint for C++, are hugely popular for the very reason that they help point out legal code that may not be what you intended. I'm jolly grateful that my C++ compiler always points out when I do this:-    if (x = y) Very rarely I may want to do just this, but I'll write the slightly longer form to placate the compiler:-    if ((file = fopen(...) != NULL) C# may not have nearly as many dark corners as C++, but it has some. The Visual C++ team added a separate switch "/analyze" as less intrusive method which may be a preferable approach. Those who know what they're doing and dislike being nannied can do so. The rest of us who know that we are fallible have the opportunity to get all the help we can lay our hands on.

  • Anonymous
    November 17, 2009
    Isn't this known as lexical closures? Switching from this to closures that behave like they do in scheme or ruby seems more like adding a new language feature than fixing a bug. First off, scheme closures and ruby closures both use lexical closures. You seem to be implying that they use dynamic scoping. Second, I don't see what the difference between lexical and dynamic scoping has to do with it. The question of whether a closure ought to close over a variable or a value seems germane, but I don't see why whether the binding is lexical or dynamic is relevant. Can you clarify why you think this is relevant? Third, the proposal at hand is NOT to change how closures work; closures in C# are lexical closures that close over variables and that's not changing. The proposals at hand are (1) to move the declaration of the foreach loop variable to be logically inside the loop, or (2) to produce a warning that the closure closes over a single variable, not one variable per loop iteration. I'm therefore very confused by your comment. Can you elaborate on what you're getting at here, because I'm not following you. -- Eric

  • Anonymous
    November 17, 2009
    > Scheme closures use lexical scoping; ruby closures use dynamic scoping. Eric, can you elaborate on that? I'm not a Ruby expert, but from what I've seen all closures in Ruby are lexical. They do have three different kinds:

  • blocks, which aren't first-class (you can pass a block as an argument, but you cannot store it in a variable);
  • lambdas, which are first-class, and are really most like C# lambdas in pretty much everything;
  • procs, which are like lambdas, but also "capture" flow control (so a proc can do an early return from the function in which it was created, or break from a loop if it was created in the loop body). All three kinds of closures are lexical, however, in that when you reference a variable "a" inside a closure, it will always be the variable visible in the scope in which the closure was created - not the nearest declared in the scope from which it is called. Or did you mean something else by "dynamic scoping"? I was misremembering. I was probably thinking of some other language that has dynamic scoping for closures, like Perl (optionally) or PostScript (by default). However, the point remains that I don't understand the comment. I'll fix up the text. Thanks. -- Eric
  • Anonymous
    November 17, 2009
    The comment has been removed

  • Anonymous
    November 17, 2009
    Still no answers to my question of "What is a real-world scenario where you'd want the current behavior?" It's all well and good to demonstrate the capture problem, but does someone have a real example? IMHO it's only a breaking change if there exists code out there that uses it in this way and meant to. I have a feeling there's a lot of code using the workaround to get the value they really want foreach( i in list ) {   // copy i to v, foreach capture varialble issue see http://blogs.msdn.com/ericlippert/   // will be fixed in c#5 we hope   var v = i;   funcs.Add( () => v ); } In this case, fixing the #1 foreach fix (declaration inside loop) makes no semantic difference to the resulting code. Otherwise, the code is wrong and nobody tested it. I wouldn't put it as a warning either (for the warnings-as-errors crowd), but variable capture of the foreach variable could be an 'information' message in C# 4. Also, you can still explicitly allow capturing by just declaring a variable y which is outside the foreach, which would make it clear what the value of the captured variable will be. So if there is real-world code that needs this bizarre behavior, it can still work with only minor modification.

  • Anonymous
    November 17, 2009
    The comment has been removed

  • Anonymous
    November 17, 2009
    The comment has been removed

  • Anonymous
    November 18, 2009
    @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.

  • Anonymous
    November 18, 2009
    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. :)

  • Anonymous
    November 18, 2009
    The comment has been removed

  • Anonymous
    November 18, 2009
    > 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).

  • Anonymous
    November 18, 2009
    The comment has been removed

  • Anonymous
    November 20, 2009
    The comment has been removed

  • Anonymous
    November 20, 2009
    "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." 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?

  • Anonymous
    November 20, 2009
    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.

  • Anonymous
    November 20, 2009
    The comment has been removed

  • Anonymous
    November 23, 2009
    The comment has been removed

  • Anonymous
    December 15, 2009
    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.

  • Anonymous
    December 16, 2009
    The comment has been removed

  • Anonymous
    December 26, 2009
    The comment has been removed

  • Anonymous
    January 26, 2010
    The comment has been removed

  • Anonymous
    February 06, 2010
    I'm quite late to this show (I tend to save and read blogs offline), but my vote is to change it, even if it's a breaking change. The very fact that it's a breaking change initially made me feel it should stay as-is.  But as Stuart Ballard said, it's not just unintuitive, but "unuseful".  It's hard to think of a situation in which the current behavior would be intentionally leveraged.  I think most of us, writing foreach the long way, would intuitively put the loop variable inside, not outside. While I understand the mindset of those who say it's a matter of training, I can't agree in this case.  The current behavior isn't so much a matter of closure as a matter of a quirk in the way foreach works.  (And I've been bitten by the quirk at least once, when I assigned several event handlers in a loop using lambda expressions, and then tried to figure out why only one of the handlers ever seemed to get hit.)

  • Anonymous
    April 16, 2010
    I'm even later to the game, but there's a solution that is elegant, non-breaking, and solves a wider range of problems than the foreach loop itself.  So right now the way you have to implement this is... int x = 0 foreach( i in list ) {  x += 1;  int y = x;  var z = i;  funcs1.Add( () => z );  funcs2.Add( () => y ); } What if there was a way to declaratively "pin" the values of i and x, so that when used later they retain the expected value.  For example, this could be rewritten as... int x = 0 foreach( i in list ) {  x += 1;  funcs1.Add( () => (!)i );  funcs2.Add( () => (!)x ); } That gives me a tighter syntax with (I think) a non breaking language change (if it is breaking then pick something that wouldn't break), I've covered the enumerator's case, I've covered the outer variable case, it can be easily turned on and off to support whichever model you want.  As far as I can tell, it's pure awesomeness.

  • Anonymous
    July 21, 2010
    By the way, there already is a clear syntax for that "new" behavior. If we will consider replacing -- var values = new List<int>() { 100, 110, 120 }; var funcs = new List<Func<int>>(); foreach(var v in values)  funcs.Add( ()=>v ); foreach(var f in funcs)  Console.WriteLine(f()); -- with -- var values = new List<int>() { 100, 110, 120 }; var funcs = new List<Func<int>>(); values.ForEach(v => funcs.Add(() => v)); funcs.ForEach(f => Console.WriteLine(f())); -- then the resulting program will clearly output 100, then 110, then 120 :) So there is another reason to not invent that new syntax :)

  • Anonymous
    March 29, 2011
    @Penartur: That is a function on lists.  It isn't sufficient if dealing with collections other than lists.

  • Anonymous
    June 15, 2011
    The comment has been removed