Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The issue here is largely one of good practice and preventing against inadvertent mistakes. Admittedly, the C# compiler <em>could theoretically</em> be designed such that there is no conflict between scopes here. This would however be much effort for little gain, as I see it.</p> <p>Consider that if the declaration of <code>var</code> in the parent scope were <em>before</em> the if statement, there would be an unresolvable naming conflict. The compiler simply does not differentiate between the following two cases. Analysis is done <em>purely based on scope</em>, and not order of declaration/use, as you seem to be expecting.</p> <p>The theoretically acceptable (but still invalid as far as C# is concerned):</p> <pre><code>if(true) { string var = "VAR"; } string var = "New VAR!"; </code></pre> <p>and the unacceptable (since it would be hiding the parent variable):</p> <pre><code>string var = "New VAR!"; if(true) { string var = "VAR"; } </code></pre> <p>are both treated precisely the same in terms of variables and scopes.</p> <p>Now, is there any actual reason in this secenario why you can't just give one of the variables a different name? I assume (hope) your actual variables aren't called <code>var</code>, so I don't really see this being a problem. If you're still intent on reusing the same variable name, just put them in sibling scopes:</p> <pre><code>if(true) { string var = "VAR"; } { string var = "New VAR!"; } </code></pre> <p>This however, while valid to the compiler, can lead to some amount of confusion when reading the code, so I recommend against it in almost any case.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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