Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a reason for C#'s reuse of the variable in a foreach?
    primarykey
    data
    text
    <p>When using lambda expressions or anonymous methods in C#, we have to be wary of the <em>access to modified closure</em> pitfall. For example:</p> <pre><code>foreach (var s in strings) { query = query.Where(i =&gt; i.Prop == s); // access to modified closure ... } </code></pre> <p>Due to the modified closure, the above code will cause all of the <code>Where</code> clauses on the query to be based on the final value of <code>s</code>.</p> <p>As explained <a href="http://resnikb.wordpress.com/2009/06/17/c-lambda-and-foreach-variable/" rel="noreferrer">here</a>, this happens because the <code>s</code> variable declared in <code>foreach</code> loop above is translated like this in the compiler:</p> <pre><code>string s; while (enumerator.MoveNext()) { s = enumerator.Current; ... } </code></pre> <p>instead of like this:</p> <pre><code>while (enumerator.MoveNext()) { string s; s = enumerator.Current; ... } </code></pre> <p>As pointed out <a href="https://stackoverflow.com/a/2388644/120955">here</a>, 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:</p> <pre><code>string s; while (enumerator.MoveNext()) { s = enumerator.Current; ... } var finalString = s; </code></pre> <p>However variables defined in a <code>foreach</code> loop cannot be used outside the loop:</p> <pre><code>foreach(string s in strings) { } var finalString = s; // won't work: you're outside the scope. </code></pre> <p>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.</p> <p>Is there something you can do with <code>foreach</code> 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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload