Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:</p> <pre><code>// File1.cs using System; namespace Outer.Inner { class Foo { static void Bar() { double d = Math.PI; } } } </code></pre> <p>Now imagine that someone adds another file (File2.cs) to the project that looks like this:</p> <pre><code>// File2.cs namespace Outer { class Math { } } </code></pre> <p>The compiler searches <code>Outer</code> before looking at those <code>using</code> directives outside the namespace, so it finds <code>Outer.Math</code> instead of <code>System.Math</code>. Unfortunately (or perhaps fortunately?), <code>Outer.Math</code> has no <code>PI</code> member, so File1 is now broken.</p> <p>This changes if you put the <code>using</code> inside your namespace declaration, as follows:</p> <pre><code>// File1b.cs namespace Outer.Inner { using System; class Foo { static void Bar() { double d = Math.PI; } } } </code></pre> <p>Now the compiler searches <code>System</code> before searching <code>Outer</code>, finds <code>System.Math</code>, and all is well.</p> <p>Some would argue that <code>Math</code> might be a bad name for a user-defined class, since there's already one in <code>System</code>; the point here is just that there <em>is</em> a difference, and it affects the maintainability of your code.</p> <p>It's also interesting to note what happens if <code>Foo</code> is in namespace <code>Outer</code>, rather than <code>Outer.Inner</code>. In that case, adding <code>Outer.Math</code> in File2 breaks File1 regardless of where the <code>using</code> goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any <code>using</code> directive.</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