Skip to main content

Is there a reason for C#"s reuse of the variable in a foreach?


When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example:




foreach (var s in strings)
{
query = query.Where(i => i.Prop == s); // access to modified closure



Due to the modified closure, the above code will cause all of the Where clauses on the query to be based on the final value of s .



As explained here , this happens because the s variable declared in foreach loop above is translated like this in the compiler:




string s;
while (enumerator.MoveNext())
{
s = enumerator.Current;
...



... instead of like this:




while (enumerator.MoveNext())
{
string s;
s = enumerator.Current;



As pointed out here , there are no performance advantages to declaring a variable outside the loop, and under normal circumstances the only reason I can think of for doing this is if you plan to use the variable outside the scope of the loop:




} // end while
var finalString = s;



However, variables defined in a foreach loop cannot be used outside the loop:




foreach(string s in strings)
{
}
var finalString = s; // won't work: you're outside the scope.



So the compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.



Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable, or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.


    Your criticism is entirely justified.

    I discuss this problem in detail here:

    Closing over the loop variable considered harmful


    Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?


    The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it make no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

    I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

    The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

    ReplyDelete
  2. What you are asking is thoroughly covered by Eric Lippert in his blog post Closing over the loop variable considered harmful and its sequel.

    For me, the most convincing argument is that having new variable in each iteration would be inconsistent with for(;;) style loop. Would you expect to have a new int i in each iteration of for (int i = 0; i < 10; i++)?

    The most common problem with this behavior is making a closure over iteration variable and it has an easy workaround:

    foreach (var s in strings)
    {
    var s_for_closure = s;
    query = query.Where(i => i.Prop == s_for_closure); // access to modified closure


    My blog post about this issue: Closure over foreach variable in C#.

    ReplyDelete
  3. Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example

    foreach (var s in strings)
    {
    query = query.Where(i => i.Prop == s); // access to modified closure


    I do:

    foreach (var s in strings)
    {
    string search = s;
    query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.


    Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have every done so.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex