The difference between a using statement inside a namespace and out

I honestly didn’t think that there was a difference between the locations of your using statements in C#, be they in or outside of a namespace, but I just ran into a strange situation where the difference will cause a build error. If you’re wondering what I mean by “in a namespace” please examine the following code.

namespace Example.Program
{
      using Example.Sample;
 
      class Program
      {
            static void Main(string[] args)
            {
                  Something s = new Something();
            }
      }
}
This is legitimate code and will compile just fine. So you can either have your using statements outside of a namespace and in the same file or inside of the namespace. There is a slight difference however, inside of your namespace your using statements may interpret parts of the following namespace as classes while outside it will always resolve as a namespace. For example, the following causes a build error.
namespace Example.Program
{
      using Example.Sample;
 
      class Program
      {
            static void Main(string[] args)
            {
                  Something s = new Something();
            }
      }
}
 
namespace Example.Sample
{
      public class Something { }
}
 
namespace Example
{
      public class Example
      {
      }
}
Error   1: The type name ‘Sample’ does not exist in the type ‘Example.Example’
Error   2: The type or namespace name ‘Something’ could not be found (are you missing a using directive or an assembly reference?)
Error   3: The type or namespace name ‘Something’ could not be found (are you missing a using directive or an assembly reference?)
 
I’m not sure why this difference is here or what the benefit is but for better or worse this is how it works. You could also argue that it’s not a good idea to have a class name conflict with a namespace name but, unfortunately, this isn’t always under your own control.
So the thing is that putting your using statements outside of your namespace seems to fix these build errors, so I don’t know why it would ever be preferable to put these using statements inside of your namespace (as recommended by StyleCop by default, for example).

Author: justinmchase

I'm a Software Developer from Minnesota.

Drop a brain bomb

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s