views:

53

answers:

3

What is exact difference in writing USING directives before or after namespace declaration.

Example :

using System;
using System.Linq;
using NUnit.Framework;

namespace HostTest
{
 /**  code goes here **/
}

and

namespace HostService
{
  using System.Runtime.Serialization;
  using System;

       /**  code goes here **/
}
+2  A: 

If you put the using inside the namespace they apply only to this namespace and not to other namespaces in the same file. This allows you to do the following:

namespace Bar
{
    public class Foo { }
}

namespace Foo
{
    using Bar;

    public class Test
    {
        public Test()
        {
            var f = new Foo();
        }
    }
}

Notice how the Foo class is used inside the Foo namespace thanks to the using Bar inside.

Darin Dimitrov
A: 

Totally agree with Darin. To add to what Darin just mentioned... I tried creating two Console Applications and changed the order of usings the way you suggested. I checked the EXEs in .NET Reflecteor and there was absolutely no difference. It is just about the way you would like to use the usings.

Rahul Soni
+3  A: 

Darin's answer is correct but not comprehensive - because it also makes a difference to how the using directives themselves perform lookup: whether they attempt to match the names within another namespace.

Eric Lippert has a great blog post going into more details. To my mind, the most important point is at the end:

Therefore my advice is now:

  • have only one top-level namespace per file
  • if you choose to put using directives inside your namespaces then fully qualify them with the global alias qualifier

As a corollary, I'd suggest that as the second point means that using directives inside namespaces are trickier to get right than using directives outside namespaces, I'd go with putting them outside. It also helps that that's the Visual Studio default :)

This is all just a compile-time issue though - it only affects how the compiler looks up names, not what the generated code using those names looks like.

One final point of terminology: your question talks about using statements, but all of these are using directives. The using statement is the one that acquires a resource and disposes of it at the end:

using (Stream stream = ...)
{
    // ...
}

I mention this only in the spirit of further education - it was obvious what you meant in this particular case :)

Jon Skeet
Thanks a lot Jon , for Clarification and correcting me :)
openidsujoy