Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Visual Studio uses an <a href="http://blogs.msdn.com/b/ed_maurer/archive/2008/06/11/a-tale-of-two-compilers.aspx" rel="nofollow noreferrer">in-process compiler</a>, so it knows which version of C# it's using.</p> <p>As you noted, csc.exe from the command line, on the other hand, uses whatever C# version it's made to compile, so in your case it'll be C# 5.0. Since it's an in-place upgrade (in terms of installation directory), it might break code that relied on the <code>foreach</code> binding being the same across the whole loop (odd, but possible).</p> <hr> <blockquote> <p>NOTE: Old answer for the wrong question: the OP knows this and was testing it from the command line.</p> </blockquote> <p>The blog post you link to already answers your question. I think this question is related to <a href="https://stackoverflow.com/q/12112881">this one</a>.</p> <p>It's the compiler that changed, so this:</p> <pre><code>foreach (int value in values) { // ... } </code></pre> <p>used to generate something along the following code:</p> <pre><code>{ int value; for (/* iteration */) { value = /* get from enumerator */; // ... } } </code></pre> <p>while the new C# compiler now generates the equivalent of moving the variable to inside the loop:</p> <pre><code>for (/* iteration */) { int value = /* get from enumerator */; // ... } </code></pre> <p>This makes a great difference, since closures within the <code>// ...</code> will capture a new <code>value</code> binding in each cycle, instead of sharing the same <code>value</code> binding that used to be declared outside the loop.</p> <p>The catch is, if you want your code to work correctly for both older and newer compilers, you must declare your own variable inside the <code>foreach</code> loop:</p> <pre><code>foreach (int value in values) { int newValue = value; // ... } </code></pre> <hr> <p>The current C# 4.0 specification in Visual Studio 2010 says:</p> <blockquote> <p>(...) A foreach statement of the form</p> <pre><code>foreach (V v in x) embedded-statement </code></pre> <p>is then expanded to:</p> <pre><code>{ E e = ((C)(x)).GetEnumerator(); try { V v; while (e.MoveNext()) { v = (V)(T)e.Current; embedded-statement } } finally { … // Dispose e } } </code></pre> </blockquote> <p>The C# 5.0 specification in Visual Studio 2012 says:</p> <blockquote> <p>(...) A foreach statement of the form</p> <pre><code>foreach (V v in x) embedded-statement </code></pre> <p>is then expanded to:</p> <pre><code>{ E e = ((C)(x)).GetEnumerator(); try { while (e.MoveNext()) { V v = (V)(T)e.Current; embedded-statement } } finally { … // Dispose e } } </code></pre> </blockquote>
 

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