Can anyone explain the below demo with closures. RRS feed


  • It is for exactly the reason explained in the link you provided, but as per the "Update" section at the top of that page, this problem only occurred prior to C#5.

    Basically, the delegate ()=> v would compile as a "function that returns the variable v", where v was declared outside the loop. This gives you a set of functions that all just returned whatever the current value of v is at the end of the foreach.

    So when you then loop around the generated functions and call them, they will all just return the current value of v, which would all be the same value.

    See that page where it explains that the foreach loop is really just a shorthand for an expanded bit of code that referenced a variable declared outside the loop.

    As of C# 5, this behaviour was changed (a breaking change), so as to refer to a variable inside the loop instead. So now you get the behaviour you expect (an output of 100,110,120).

    • Edited by RJP1973 Monday, November 27, 2017 2:10 PM
    • Proposed as answer by Fei HuModerator Tuesday, November 28, 2017 12:19 PM
    • Marked as answer by Aimee.Young Monday, December 4, 2017 2:59 PM
    Monday, November 27, 2017 2:08 PM