52

This works fine (means as expected) in C# 5.0:

var actions = new List<Action>();
foreach (var i in Enumerable.Range(0, 10))
{
    actions.Add(() => Console.WriteLine(i));
}
foreach (var act in actions) act();

Prints 0 to 9. But this one shows 10 for 10 times:

var actions = new List<Action>();
for (var i = 0; i < 10; i++)
{
    actions.Add(() => Console.WriteLine(i));
}
foreach (var act in actions) act();

Question: This was a problem that we had in C# versions before 5.0; so we had to use a loop-local placeholder for the closure and it's fixed now - in C# 5.0 - in "foreach" loops. But not in "for" loops!

What is the reasoning behind this (not fixing the problem for for loops too)?

17
  • 3
    Do you mean "what's the reasoning for it not being fixed for for loops as well"?
    – Jon Skeet
    Apr 28, 2013 at 15:15
  • 1
    @LightStriker: No; it's a feature. It's called a closure.
    – SLaks
    Apr 28, 2013 at 15:18
  • 3
    It doesn't assume.. it extends the lifetime of the var i depending on the scope of the lambdas IIRC Apr 28, 2013 at 15:21
  • 3
    @LightStriker: Absolutely. For example: public IEnumerable<Person> FindAdults(int minimumAge) { return people.Where(p => p.Age >= minimumAge); } By the time that predicate is executed, the parameter won't be in scope any more. Without that ability to capture variables, LINQ would be massively weaker.
    – Jon Skeet
    Apr 28, 2013 at 15:42
  • 2
    @LightStriker: Well in the method I showed, nothing else could change that variable, could it? It's a local variable to that method, as it's a parameter. But in other cases, yes that can happen if you play fast and loose. But I'd say the problem here is your expectation more than anything - you expect a behaviour which is contrary to the clearly-defined behaviour in the specification.
    – Jon Skeet
    Apr 28, 2013 at 16:12

1 Answer 1

49

What is the reasoning behind this?

I'm going to assume you mean "why wasn't it changed for for loops as well?"

The answer is that for for loops, the existing behaviour makes perfect sense. If you break a for loop into:

  • initializer
  • condition
  • iterator
  • body

... then the loop is roughly:

{
    initializer;
    while (condition)
    {
        body;
        iterator;
    }
}

(Except that the iterator is executed at the end of a continue; statement as well, of course.)

The initialization part logically only happens once, so it's entirely logical that there's only one "variable instantiation". Furthermore, there's no natural "initial" value of the variable on each iteration of the loop - there's nothing to say that a for loop has to be of a form declaring a variable in the initializer, testing it in the condition and modifying it in the iterator. What would you expect a loop like this to do:

for (int i = 0, j = 10; i < j; i++)
{
    if (someCondition)
    {
        j++;
    }
    actions.Add(() => Console.WriteLine(i, j));
}

Compare that with a foreach loop which looks like you're declaring a separate variable for every iteration. Heck, the variable is read-only, making it even more odd to think of it being one variable which changes between iterations. It makes perfect sense to think of a foreach loop as declaring a new read-only variable on each iteration with its value taken from the iterator.

4
  • 7
    (It's hard for me to argue with a high rank developer with a 559k beside his picture; yet:) Common sense (the part restricted to boundaries of my mind) tends to disagree and in many other languages you can see that for acts as both for and foreach. Let's rewrite the while loop this way: var x = initializer(); while(condition) { feed_x_to_body(body); x = iterator(); } and I expect that feed_x_to_body (which is a job for compiler) does it's job as expected (not as what is logical according to underlying implementation - that's of compiler's interest not me!). Maybe I am wrong; please guide more. Apr 28, 2013 at 15:48
  • 2
    @KavehShahbazian: No, that's not how a for loop works. The fact that many for loops happen to declare exactly one variable in the initializer is irrelevant. The variable declared in the initializer is the variable which is used in the body of the loop - it's not that the body is given a variable value. In particular, the body of the loop can modify the variable as well, which would break your model of the world.
    – Jon Skeet
    Apr 28, 2013 at 15:51
  • 1
    "Being able to modifying the variable" made it clear to me. Yet I think when I create a new scope (like a lambda body) the value of variable should become detached from it's main scope. That part still has not found it's place in my mind and It would be very kind of you to guide more about that part. But I mark your response as answer because it fits (current) C# world. Thanks; Apr 28, 2013 at 16:00
  • 3
    @KavehShahbazian: Well, simply put "it doesn't"! In C#, the variable is captured, not its value. So the lambda expression can change the variable, and changes to the variable from outside the lambda expression can be seen within the lambda expression.
    – Jon Skeet
    Apr 28, 2013 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.