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
- Lowers the chances of namespace pollution in case the source file has more than one namespace declaration in it
- Reduces the size of the drop down in intellisense
- 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 { }}
Comments
Anonymous
August 21, 2006
<<<
There are two ways in which you can use using statements as outlined below
>>>
Small correction: It's a using directive - not a using statement.
"using statement" are what you use for resource aquisition.Anonymous
August 21, 2006
yea, its a directive. I'll fix this....Anonymous
February 08, 2008
Thanks for the tip for aliasing.Anonymous
June 02, 2008
The comment has been removedAnonymous
June 16, 2015
Another main reason is: if we wanted our solution (more than one project) to export as template using Visual studio menu option (File -> Export Template). So if using are inside names spaces it resolves dependencies automatically when we export project solution as template.