Hacker News new | ask | show | jobs
by joelangeway 5206 days ago
I confess to making the mistake many times of thinking that I was capturing a value when I was capturing a variable, but the author has me confused and concerned that the semantics of lambdas have been changed such that a lambda always captures the value and not the variable. Capturing variables is darn useful and more general than capturing values. It would be totally unlike MS to break all of my code as much as I wish they would in other cases, so I'm going to assume that they've done something more clever than that.
2 comments

They haven't actually changes the lambda code at all, they have only changed the fact that previously the foreach variable was declared outside the loop, now it is declared inside the scope. The lambda still closes over the loop variable. If you code your own loop, feel free to declare the loop entities anywhere you like.
Exactly, I also find it a bit confusing. I assume they are capturing variables (it would be crazy otherwise!) but they treat loop variables differently (as if a new variable was created every time).
Yes, they are now creating a new variable in the `foreach` loop each time.

They aren't doing the same for regular `for` loops so their behavior with respect to lambdas won't change.

To add to this, Eric Lippert, a principal dev on the C# compiler team, mentions this in a StackOverflow response (http://stackoverflow.com/a/8899347/59111). He also blogged about the issue in general in a two part series, the first of which can be read here: Closing over the loop variable considered harmful (http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closi...).