Stylistic differences in using

There are two ways in which you can use using directive as outlined below

Style 1

 using System;using System.Collections.Generic;using System.Text;namespace MyNameSpace{    // ...}

Style 2

 namespace MyNameSpace{     using System;    using System.Collections.Generic;    using System.Text;    // ...}

With respect to scoping both the styles have the same effect on all the code inside the MyNameSpace.

Microsoft tools seem to differ in which style is preferred. Style-1 is used by the source template in the CSharp projects, so if you create a new project the files generated will use the first style. However, in case you use CodeDom to generate code in C#, it uses the second style (note in VB.NET it uses the first style).

Stylecop also fails the first style with the note that Using directives must be inside of a namespace element.

I am using CodeDom to generate some code and I tried to figure out the benefits of the 2nd style as the code is generated in that format. I found out the following benefits

  1. Lowers the chances of namespace pollution in case the source file has more than one namespace declaration in it
  2. Reduces the size of the drop down in intellisense
  3. Conflict detection in aliasing

Jay Thaler pointed me out the last one. The example goes as follows

 using System;using Uri = System.Uri; namespace MyNamespace{    public class MyClass    {        public void DoIt()        {            new Uri();        }    }    public class Uri    {    }}

In this code the class Uri will silently override the Uri alias. However, compilation of the following will fail with error CS0576: Namespace 'MyNamespace' contains a definition conflicting with alias 'Uri'

 namespace MyNamespace{    using System;    using Uri = System.Uri;     public class MyClass    {        public void DoIt()        {            new Uri();        }    }    public class Uri    {    }}