4 ms·
Here's hoping they fix closures in C# 5. (ref: http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx ht
by dschobel 16y ago
Here's hoping they fix closures in C# 5.
(ref: http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closi... )
- trezor 16y agoI wouldn't go so far to say as there is anything wrong in closures itself, as much as a special case with regard to how it plays out in combination with the way the iterator pattern is integrated into the language itself. I agree that in the example provided it does seem counter-intuitive at first, but v is clearly a variable tied to the the loop and there is nothing that explicitly tells us if it is scoped outside the loop or to the code-block within the loop. If anything, I'd say it's the implementation of the iterator pattern which is broken, not the closures themselves (which I've had zero issues with).
- bad_user 16y agoClosures close over variables, not over values; the behavior in C# is correct in this regard.
- dschobel 16y agoI'm well aware of what the implementation is. If you read the reference, closing over variables is one of the most common source of customer complaints about a "bug" in the compiler as the implementation is completely counter-intuitive until you look at the MSIL. Ergo, they should fix closures.
- sid0 16y agoYeah, I've been bitten by this more than once while writing code using for-each and Iterator in JavaScript. It is definitely counter-intuitive.
- bad_user 16y agoWhat people that get bitten don't get: closures are lazy. They aren't executed right away unless you want to. That's their purpose, with the most common use-case being to postpone a piece of computation for later (until you've got everything you need). So it cannot close over values, and if it did it would mean that you couldn't modify the values from the outer-scope (which you just closed over) ... making closures totally useless.
- sid0 16y agoThe way it seems counter-intuitive to me is that I think of each loop iteration as containing a fresh variable, and not the same variable being re-assigned to over and over again.
- MichaelGG 16y agoWell, F# doesn't allow closures to access local mutable variables, and they don't seem "totally useless". In the case of a for loop, F# seems more intuitive: if you loop and generate closures using the loop variable, each closure will get the value at the time its created. This isn't as straightforward in C#, as there are no immutable local bindings. It's annoying, but given the overall language, is probably the best fit.
- barrkel 16y agoYou misread your own link: closing over loop variables considered harmful. Closing over values rather than variables would make closures useless for a huge variety of purposes.