Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Most</strong> of the time, it does not matter whether you declare a variable inside or outside the loop; the rules of definite assignment ensure that it doesn't matter. In the debugger you might occasionally see old values (i.e. if you look at a variable in a breakpoint before it is assigned), but static-analysis proves that this won't impact executing code. The variables are never reset per loop, as there is demonstrably no need.</p> <p>At the IL level, **usually* the variable is declared just once for the method - the placement inside the loop is just a convenience for us programmers.</p> <p><strong>HOWEVER</strong> there is an important exception; any time a variable is captured, the scoping rules get more complex. For example (2 secs):</p> <pre><code> int value; for (int i = 0; i &lt; 5; i++) { value = i; ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(value); }); } Console.ReadLine(); </code></pre> <p>Is <strong>very</strong> different to:</p> <pre><code> for (int i = 0; i &lt; 5; i++) { int value = i; ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(value); }); } Console.ReadLine(); </code></pre> <p>As the "value" in the second example is <strong>truly</strong> per instance, since it is captured. This means that the first example might show (for example) "4 4 4 4 4", where-as the second example will show 0-5 (in any order) - i.e. "1 2 5 3 4".</p> <p>So: were captures involved in the original code? Anything with a lambda, an anonymous method, or a LINQ query would qualify.</p>
 

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