views:

366

answers:

2

What is the difference between

namespace x
{
  using y;
}

and

using y;
namespace x
{
}

?

+11  A: 

The first one has y in scope for just the namespace x, the second has y in scope for the whole file, so potentialy other namespaces. If you keep to one namespace per file (I'd guess that was the convention) then there's usually no real difference [but see Marc's comment about clashes if different types have the same name in different namespaces]. If you use StyleCop it will want you to keep the usings inside the namespace.

Steve Haigh
Actually, I seem to recall that there *can* be a difference... *if* there are conflicting types etc at different levels.
Marc Gravell
And as another (more practical) difference... one of them can crash the LINQ-to-SQL code generator, and one doesn't ;-p
Marc Gravell
Good point Marc, will edit.
Steve Haigh
+6  A: 

Putting the using statement inside the namespace block scopes it to that block. This affects a number of things.

  1. As @Steve Haigh mentioned, the using statement is only valid within the block, so if there were other namespace blocks, they wouldn't be affected.
  2. The namespace specified by the using can be shortened based on the outer namespace block. So using x.y; outside of the namespace can just be expressed as using y; inside of the namespace x block.
  3. Putting the using inside of the namespace causes the compiler to guarantee that the specified namespace isn't overwritten. For example:
        using Guid = System.Guid;
        namespace Sample
        {
            public class Guid {}
            public class Program
            {
                public static void Main()
                {
                    Console.WriteLine(new Guid());
                }
            }
        }
    The above code will compile, but it is unclear which Guid is being instantiated. If the using statement is inside of the namespace block, however, a compiler error is thrown.

See the related StyleCop documentation for a more complete discussion.

bdukes
+1. Interesting edge case there.
Steve Haigh