Related
begginers question about C#.
In every program I have to include several namespaces, like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Why do I have to include:
using System.Collections.Generic;
using System.Linq;
using System.Text;
... since they are included with first one:
using System;
Thank you in advance!
Because nested namespaces are not included with parent one. See using directive documentation for details
A using directive does not give you access to any namespaces that are nested in the namespace you specify.
System and System.IO namespaces are different.
You can treat "subnamespace" as parent-child relationship in the object model. If you have access to the "Car" object does not mean that you have access to car's wheels.
System is a huge namespace that contains hundreds of nested namespace and thousands of classes. You should specify all nested namespaces separately to state what part of the module are you interested in.
Imagine these namespaces with these classes (the last name is a class):
A.B.Class1
A.Class2
Now you have the following:
using A - allows you to refer to Class2 directly... but not to Class1.
using A.B - allows you to refer to Class1 directly but not to Class2.
If you want to refer to both classes directly in your code, you need both usings.
System and System.Text are two different namespaces. That System.Text seems to be a part of System is the semantics we as programmer put into it. There's no such thing as a nested namespace from a platform view;
But even if that was not the case what should happen if you had
namespace MySystem{
namespace Foo{
class Bar {...}
}
class Bar{...}
}
using MySystem;
class MyClass{
private Bar _myBar; //Which one is it MySystem.Foo.Bar or MySystem.Bar?
}
Since you're beginner let me clarify one thing namespace in C# and package in Java are different things. no need to merge them.
Not all classes in .net is inside one big container.Doing so increases the chance of class name collision and it doesn't look good in the first place.Namespaces are containers that try to keep your library clean and make more sense.Having a FTP class and String class together under one container does not logically make any sense.They do two different things and they should be kept in separate containers.
Also a namespace can be nested.Sometime A namespace can all but have just another namespace,without any class.so to access a class you need to qualify the full namespace before you can use it.
In your case you use different classes ,which are on different containers.So if you need them you need to qualify them with their namespace.
Just an added example to make you understand clearly.
A child Namespace cant be accessed by calling parent namespaces
Namespace Main //only code and classes are accessible
{
//code for Main Namespace
Namespace subMain //only code and classes are accessible
{
//code for subMain
Namespace verySubMain //only code and classes are accessible
{
//code for verySubMain
}
Namespace otherVerySubMain //only code and classes are accessible
{
//code for otherVerySubMain
}
}
}
If you wanted access to a class in System.Text without the using statement, you would have to Text."Name of class/function" every time you wished to use it.
This way you can just call "name of class/function".
Not sure if you are a beginner, but that's the simplest way I can describe put it.
I have been running StyleCop over some C# code, and it keeps reporting that my using directives should be inside the namespace.
Is there a technical reason for putting the using directives inside instead of outside the namespace?
There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:
// File1.cs
using System;
namespace Outer.Inner
{
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
Now imagine that someone adds another file (File2.cs) to the project that looks like this:
// File2.cs
namespace Outer
{
class Math
{
}
}
The compiler searches Outer before looking at those using directives outside the namespace, so it finds Outer.Math instead of System.Math. Unfortunately (or perhaps fortunately?), Outer.Math has no PI member, so File1 is now broken.
This changes if you put the using inside your namespace declaration, as follows:
// File1b.cs
namespace Outer.Inner
{
using System;
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
Now the compiler searches System before searching Outer, finds System.Math, and all is well.
Some would argue that Math might be a bad name for a user-defined class, since there's already one in System; the point here is just that there is a difference, and it affects the maintainability of your code.
It's also interesting to note what happens if Foo is in namespace Outer, rather than Outer.Inner. In that case, adding Outer.Math in File2 breaks File1 regardless of where the using goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any using directive.
This thread already has some great answers, but I feel I can bring a little more detail with this additional answer.
First, remember that a namespace declaration with periods, like:
namespace MyCorp.TheProduct.SomeModule.Utilities
{
...
}
is entirely equivalent to:
namespace MyCorp
{
namespace TheProduct
{
namespace SomeModule
{
namespace Utilities
{
...
}
}
}
}
If you wanted to, you could put using directives on all of these levels. (Of course, we want to have usings in only one place, but it would be legal according to the language.)
The rule for resolving which type is implied, can be loosely stated like this: First search the inner-most "scope" for a match, if nothing is found there go out one level to the next scope and search there, and so on, until a match is found. If at some level more than one match is found, if one of the types are from the current assembly, pick that one and issue a compiler warning. Otherwise, give up (compile-time error).
Now, let's be explicit about what this means in a concrete example with the two major conventions.
(1) With usings outside:
using System;
using System.Collections.Generic;
using System.Linq;
//using MyCorp.TheProduct; <-- uncommenting this would change nothing
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
namespace MyCorp.TheProduct.SomeModule.Utilities
{
class C
{
Ambiguous a;
}
}
In the above case, to find out what type Ambiguous is, the search goes in this order:
Nested types inside C (including inherited nested types)
Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
Types in namespace MyCorp.TheProduct.SomeModule
Types in MyCorp.TheProduct
Types in MyCorp
Types in the null namespace (the global namespace)
Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty
The other convention:
(2) With usings inside:
namespace MyCorp.TheProduct.SomeModule.Utilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct; // MyCorp can be left out; this using is NOT redundant
using MyCorp.TheProduct.OtherModule; // MyCorp.TheProduct can be left out
using MyCorp.TheProduct.OtherModule.Integration; // MyCorp.TheProduct can be left out
using ThirdParty;
class C
{
Ambiguous a;
}
}
Now, search for the type Ambiguous goes in this order:
Nested types inside C (including inherited nested types)
Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty
Types in namespace MyCorp.TheProduct.SomeModule
Types in MyCorp
Types in the null namespace (the global namespace)
(Note that MyCorp.TheProduct was a part of "3." and was therefore not needed between "4." and "5.".)
Concluding remarks
No matter if you put the usings inside or outside the namespace declaration, there's always the possibility that someone later adds a new type with identical name to one of the namespaces which have higher priority.
Also, if a nested namespace has the same name as a type, it can cause problems.
It is always dangerous to move the usings from one location to another because the search hierarchy changes, and another type may be found. Therefore, choose one convention and stick to it, so that you won't have to ever move usings.
Visual Studio's templates, by default, put the usings outside of the namespace (for example if you make VS generate a new class in a new file).
One (tiny) advantage of having usings outside is that you can then utilize the using directives for a global attribute, for example [assembly: ComVisible(false)] instead of [assembly: System.Runtime.InteropServices.ComVisible(false)].
Update about file-scoped namespace declarations
Since C# 10.0 (from 2021), you can avoid indentation and use either (convention 1, usings outside):
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
namespace MyCorp.TheProduct.SomeModule.Utilities;
class C
{
Ambiguous a;
}
or (convention 2, usings inside):
namespace MyCorp.TheProduct.SomeModule.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct;
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
class C
{
Ambiguous a;
}
But the same considerations as before apply.
Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make much of a difference whether they go outside or inside the namespace.
using ThisNamespace.IsImported.InAllNamespaces.Here;
namespace Namespace1
{
using ThisNamespace.IsImported.InNamespace1.AndNamespace2;
namespace Namespace2
{
using ThisNamespace.IsImported.InJustNamespace2;
}
}
namespace Namespace3
{
using ThisNamespace.IsImported.InJustNamespace3;
}
According to Hanselman - Using Directive and Assembly Loading... and other such articles there is technically no difference.
My preference is to put them outside of namespaces.
According the to StyleCop Documentation:
SA1200: UsingDirectivesMustBePlacedWithinNamespace
Cause
A C# using directive is placed outside of a namespace element.
Rule Description
A violation of this rule occurs when a using directive or a using-alias directive is placed outside of a namespace element, unless the file does not contain any namespace elements.
For example, the following code would result in two violations of this rule.
using System;
using Guid = System.Guid;
namespace Microsoft.Sample
{
public class Program
{
}
}
The following code, however, would not result in any violations of this rule:
namespace Microsoft.Sample
{
using System;
using Guid = System.Guid;
public class Program
{
}
}
This code will compile cleanly, without any compiler errors. However, it is unclear which version of the Guid type is being allocated. If the using directive is moved inside of the namespace, as shown below, a compiler error will occur:
namespace Microsoft.Sample
{
using Guid = System.Guid;
public class Guid
{
public Guid(string s)
{
}
}
public class Program
{
public static void Main(string[] args)
{
Guid g = new Guid("hello");
}
}
}
The code fails on the following compiler error, found on the line containing Guid g = new Guid("hello");
CS0576: Namespace 'Microsoft.Sample' contains a definition conflicting with alias 'Guid'
The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code.
When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error.
Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose.
Placing using-alias directives within the namespace element eliminates this as a source of bugs.
Multiple Namespaces
Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.
It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.
How to Fix Violations
To fix a violation of this rule, move all using directives and using-alias directives within the namespace element.
There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier using statements and has to be fully qualified.
Consider:
namespace MyNamespace
{
using System;
using MyAlias = System.DateTime;
class MyClass
{
}
}
versus:
using System;
namespace MyNamespace
{
using MyAlias = DateTime;
class MyClass
{
}
}
This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):
using MyAlias = Tuple<Expression<Func<DateTime, object>>, Expression<Func<TimeSpan, object>>>;
With using statements inside the namespace, it suddenly becomes:
using MyAlias = System.Tuple<System.Linq.Expressions.Expression<System.Func<System.DateTime, object>>, System.Linq.Expressions.Expression<System.Func<System.TimeSpan, object>>>;
Not pretty.
One wrinkle I ran into (that isn't covered in other answers):
Suppose you have these namespaces:
Something.Other
Parent.Something.Other
When you use using Something.Other outside of a namespace Parent, it refers to the first one (Something.Other).
However if you use it inside of that namespace declaration, it refers to the second one (Parent.Something.Other)!
There is a simple solution: add the "global::" prefix: docs
namespace Parent
{
using global::Something.Other;
// etc
}
Another subtlety that I don't believe has been covered by the other answers is for when you have a class and namespace with the same name.
When you have the import inside the namespace then it will find the class. If the import is outside the namespace then the import will be ignored and the class and namespace have to be fully qualified.
//file1.cs
namespace Foo
{
class Foo
{
}
}
//file2.cs
namespace ConsoleApp3
{
using Foo;
class Program
{
static void Main(string[] args)
{
//This will allow you to use the class
Foo test = new Foo();
}
}
}
//file3.cs
using Foo; //Unused and redundant
namespace Bar
{
class Bar
{
Bar()
{
Foo.Foo test = new Foo.Foo();
Foo test = new Foo(); //will give you an error that a namespace is being used like a class.
}
}
}
As Jeppe Stig Nielsen said, this thread already has great answers, but I thought this rather obvious subtlety was worth mentioning too.
using directives specified inside namespaces can make for shorter code since they don't need to be fully qualified as when they're specified on the outside.
The following example works because the types Foo and Bar are both in the same global namespace, Outer.
Presume the code file Foo.cs:
namespace Outer.Inner
{
class Foo { }
}
And Bar.cs:
namespace Outer
{
using Outer.Inner;
class Bar
{
public Foo foo;
}
}
That may omit the outer namespace in the using directive, for short:
namespace Outer
{
using Inner;
class Bar
{
public Foo foo;
}
}
The technical reasons are discussed in the answers and I think that it comes to the personal preferences in the end since the difference is not that big and there are tradeoffs for both of them. Visual Studio's default template for creating .cs files use using directives outside of namespaces e.g.
One can adjust stylecop to check using directives outside of namespaces through adding stylecop.json file in the root of the project file with the following:
{
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"orderingRules": {
"usingDirectivesPlacement": "outsideNamespace"
}
}
}
You can create this config file in solution level and add it to your projects as 'Existing Link File' to share the config across all of your projects too.
Not already mentioned:
Placing the using directives inside the namespace declaration is an application of the well-known best programming practice of declaring everything in the smallest scope possible.
If best programming practices are second nature to you, then you do things like that automatically.
This might be the best reason for putting your using directives inside the namespace declaration, regardless of (borderline) technical (borderline) merits mentioned elsewhere; It's as simple as that.
Already mentioned but perhaps better illustrated:
Placing using directives inside the namespace avoids unnecessary repetition and makes our declarations more terse.
This is unnecessarily terse:
using Com.Acme.Products.Traps.RoadRunnerTraps;
namespace Com.Acme.Products.Traps {
This is sweet and to the point:
namespace Com.Acme.Products.Traps {
using RoadRunnerTraps;
As a rule, external using directives (System and Microsoft namespaces for example) should be placed outside the namespace directive. They are defaults that should be applied in all cases unless otherwise specified. This should include any of your own organization's internal libraries that are not part of the current project, or using directives that reference other primary namespaces in the same project. Any using directives that reference other modules in the current project and namespace should be placed inside the namespace directive. This serves two specific functions:
It provides a visual distinction between local modules and 'other' modules, meaning everything else.
It scopes the local directives to be applied preferentially over global directives.
The latter reason is significant. It means that it's harder to introduce an ambiguous reference issue that can be introduced by a change no more significant than refactoring code. That is to say, you move a method from one file to another and suddenly a bug shows up that wasn't there before. Colloquially, a 'heisenbug' - historically fiendishly difficult to track down.
It is a better practice if those default using i.e. "references" used in your source solution should be outside the namespaces and those that are "new added reference" is a good practice is you should put it inside the namespace. This is to distinguish what references are being added.
Ok, let me explain:
Whenever you start a class in .Net and let's say you have another project you've developed referenced which has non static class(es) you need to use...
You have 2 options (That I know of)
Place a using at the top of your class meaning you won't need to explicitly name the whole project each time you need it's classes
using FooBarProj;
public FooBar MyMethod()
{
FooBar fb = new FooBar();
//Do stuff
return fb;
}
Or do explicitly implement those:
public FooBarProj.FooBar MyMethod()
{
FooBarProj.FooBar fb = new FooBarProj.FooBar();
//Do stuff
return fb;
}
Does this make an effective difference at all? either efficiency at execution, compiling, whatever? or its simply a dev convenience issue?
It makes no difference after compiling the code.
Either using an using statement, or using the whole class namespace and name, is the same thing after all.
When compiling to CIL code, references to types are a single thing, each reference contains all the information, regardless of how you coded that reference.
Referencing a class with a different name
You can even rename a class if you whant, doing this:
using TheString = System.String;
Now you can refer to System.String using the name TheString in your code.
All of these produces the same compiled code
string
System.String
String (if you place using System; at the beginning)
TheString (if you place using TheString = System.String; at the beginning)
Conclusion: All using statements are just convenience.
I think it is a dev convenience issue. The first version is better in all circumstances other than there is a similar class name in different namespaces. The explicit namespace declaration before the class is needed when there are same class names in different namespaces like. Dog23.class1 and dog45.class1. Always the first version if it works. It is shorter and readable.
I have been running StyleCop over some C# code, and it keeps reporting that my using directives should be inside the namespace.
Is there a technical reason for putting the using directives inside instead of outside the namespace?
There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:
// File1.cs
using System;
namespace Outer.Inner
{
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
Now imagine that someone adds another file (File2.cs) to the project that looks like this:
// File2.cs
namespace Outer
{
class Math
{
}
}
The compiler searches Outer before looking at those using directives outside the namespace, so it finds Outer.Math instead of System.Math. Unfortunately (or perhaps fortunately?), Outer.Math has no PI member, so File1 is now broken.
This changes if you put the using inside your namespace declaration, as follows:
// File1b.cs
namespace Outer.Inner
{
using System;
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
Now the compiler searches System before searching Outer, finds System.Math, and all is well.
Some would argue that Math might be a bad name for a user-defined class, since there's already one in System; the point here is just that there is a difference, and it affects the maintainability of your code.
It's also interesting to note what happens if Foo is in namespace Outer, rather than Outer.Inner. In that case, adding Outer.Math in File2 breaks File1 regardless of where the using goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any using directive.
This thread already has some great answers, but I feel I can bring a little more detail with this additional answer.
First, remember that a namespace declaration with periods, like:
namespace MyCorp.TheProduct.SomeModule.Utilities
{
...
}
is entirely equivalent to:
namespace MyCorp
{
namespace TheProduct
{
namespace SomeModule
{
namespace Utilities
{
...
}
}
}
}
If you wanted to, you could put using directives on all of these levels. (Of course, we want to have usings in only one place, but it would be legal according to the language.)
The rule for resolving which type is implied, can be loosely stated like this: First search the inner-most "scope" for a match, if nothing is found there go out one level to the next scope and search there, and so on, until a match is found. If at some level more than one match is found, if one of the types are from the current assembly, pick that one and issue a compiler warning. Otherwise, give up (compile-time error).
Now, let's be explicit about what this means in a concrete example with the two major conventions.
(1) With usings outside:
using System;
using System.Collections.Generic;
using System.Linq;
//using MyCorp.TheProduct; <-- uncommenting this would change nothing
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
namespace MyCorp.TheProduct.SomeModule.Utilities
{
class C
{
Ambiguous a;
}
}
In the above case, to find out what type Ambiguous is, the search goes in this order:
Nested types inside C (including inherited nested types)
Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
Types in namespace MyCorp.TheProduct.SomeModule
Types in MyCorp.TheProduct
Types in MyCorp
Types in the null namespace (the global namespace)
Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty
The other convention:
(2) With usings inside:
namespace MyCorp.TheProduct.SomeModule.Utilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct; // MyCorp can be left out; this using is NOT redundant
using MyCorp.TheProduct.OtherModule; // MyCorp.TheProduct can be left out
using MyCorp.TheProduct.OtherModule.Integration; // MyCorp.TheProduct can be left out
using ThirdParty;
class C
{
Ambiguous a;
}
}
Now, search for the type Ambiguous goes in this order:
Nested types inside C (including inherited nested types)
Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty
Types in namespace MyCorp.TheProduct.SomeModule
Types in MyCorp
Types in the null namespace (the global namespace)
(Note that MyCorp.TheProduct was a part of "3." and was therefore not needed between "4." and "5.".)
Concluding remarks
No matter if you put the usings inside or outside the namespace declaration, there's always the possibility that someone later adds a new type with identical name to one of the namespaces which have higher priority.
Also, if a nested namespace has the same name as a type, it can cause problems.
It is always dangerous to move the usings from one location to another because the search hierarchy changes, and another type may be found. Therefore, choose one convention and stick to it, so that you won't have to ever move usings.
Visual Studio's templates, by default, put the usings outside of the namespace (for example if you make VS generate a new class in a new file).
One (tiny) advantage of having usings outside is that you can then utilize the using directives for a global attribute, for example [assembly: ComVisible(false)] instead of [assembly: System.Runtime.InteropServices.ComVisible(false)].
Update about file-scoped namespace declarations
Since C# 10.0 (from 2021), you can avoid indentation and use either (convention 1, usings outside):
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
namespace MyCorp.TheProduct.SomeModule.Utilities;
class C
{
Ambiguous a;
}
or (convention 2, usings inside):
namespace MyCorp.TheProduct.SomeModule.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct;
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
class C
{
Ambiguous a;
}
But the same considerations as before apply.
Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make much of a difference whether they go outside or inside the namespace.
using ThisNamespace.IsImported.InAllNamespaces.Here;
namespace Namespace1
{
using ThisNamespace.IsImported.InNamespace1.AndNamespace2;
namespace Namespace2
{
using ThisNamespace.IsImported.InJustNamespace2;
}
}
namespace Namespace3
{
using ThisNamespace.IsImported.InJustNamespace3;
}
According to Hanselman - Using Directive and Assembly Loading... and other such articles there is technically no difference.
My preference is to put them outside of namespaces.
According the to StyleCop Documentation:
SA1200: UsingDirectivesMustBePlacedWithinNamespace
Cause
A C# using directive is placed outside of a namespace element.
Rule Description
A violation of this rule occurs when a using directive or a using-alias directive is placed outside of a namespace element, unless the file does not contain any namespace elements.
For example, the following code would result in two violations of this rule.
using System;
using Guid = System.Guid;
namespace Microsoft.Sample
{
public class Program
{
}
}
The following code, however, would not result in any violations of this rule:
namespace Microsoft.Sample
{
using System;
using Guid = System.Guid;
public class Program
{
}
}
This code will compile cleanly, without any compiler errors. However, it is unclear which version of the Guid type is being allocated. If the using directive is moved inside of the namespace, as shown below, a compiler error will occur:
namespace Microsoft.Sample
{
using Guid = System.Guid;
public class Guid
{
public Guid(string s)
{
}
}
public class Program
{
public static void Main(string[] args)
{
Guid g = new Guid("hello");
}
}
}
The code fails on the following compiler error, found on the line containing Guid g = new Guid("hello");
CS0576: Namespace 'Microsoft.Sample' contains a definition conflicting with alias 'Guid'
The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code.
When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error.
Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose.
Placing using-alias directives within the namespace element eliminates this as a source of bugs.
Multiple Namespaces
Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.
It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.
How to Fix Violations
To fix a violation of this rule, move all using directives and using-alias directives within the namespace element.
There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier using statements and has to be fully qualified.
Consider:
namespace MyNamespace
{
using System;
using MyAlias = System.DateTime;
class MyClass
{
}
}
versus:
using System;
namespace MyNamespace
{
using MyAlias = DateTime;
class MyClass
{
}
}
This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):
using MyAlias = Tuple<Expression<Func<DateTime, object>>, Expression<Func<TimeSpan, object>>>;
With using statements inside the namespace, it suddenly becomes:
using MyAlias = System.Tuple<System.Linq.Expressions.Expression<System.Func<System.DateTime, object>>, System.Linq.Expressions.Expression<System.Func<System.TimeSpan, object>>>;
Not pretty.
One wrinkle I ran into (that isn't covered in other answers):
Suppose you have these namespaces:
Something.Other
Parent.Something.Other
When you use using Something.Other outside of a namespace Parent, it refers to the first one (Something.Other).
However if you use it inside of that namespace declaration, it refers to the second one (Parent.Something.Other)!
There is a simple solution: add the "global::" prefix: docs
namespace Parent
{
using global::Something.Other;
// etc
}
Another subtlety that I don't believe has been covered by the other answers is for when you have a class and namespace with the same name.
When you have the import inside the namespace then it will find the class. If the import is outside the namespace then the import will be ignored and the class and namespace have to be fully qualified.
//file1.cs
namespace Foo
{
class Foo
{
}
}
//file2.cs
namespace ConsoleApp3
{
using Foo;
class Program
{
static void Main(string[] args)
{
//This will allow you to use the class
Foo test = new Foo();
}
}
}
//file3.cs
using Foo; //Unused and redundant
namespace Bar
{
class Bar
{
Bar()
{
Foo.Foo test = new Foo.Foo();
Foo test = new Foo(); //will give you an error that a namespace is being used like a class.
}
}
}
As Jeppe Stig Nielsen said, this thread already has great answers, but I thought this rather obvious subtlety was worth mentioning too.
using directives specified inside namespaces can make for shorter code since they don't need to be fully qualified as when they're specified on the outside.
The following example works because the types Foo and Bar are both in the same global namespace, Outer.
Presume the code file Foo.cs:
namespace Outer.Inner
{
class Foo { }
}
And Bar.cs:
namespace Outer
{
using Outer.Inner;
class Bar
{
public Foo foo;
}
}
That may omit the outer namespace in the using directive, for short:
namespace Outer
{
using Inner;
class Bar
{
public Foo foo;
}
}
The technical reasons are discussed in the answers and I think that it comes to the personal preferences in the end since the difference is not that big and there are tradeoffs for both of them. Visual Studio's default template for creating .cs files use using directives outside of namespaces e.g.
One can adjust stylecop to check using directives outside of namespaces through adding stylecop.json file in the root of the project file with the following:
{
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"orderingRules": {
"usingDirectivesPlacement": "outsideNamespace"
}
}
}
You can create this config file in solution level and add it to your projects as 'Existing Link File' to share the config across all of your projects too.
Not already mentioned:
Placing the using directives inside the namespace declaration is an application of the well-known best programming practice of declaring everything in the smallest scope possible.
If best programming practices are second nature to you, then you do things like that automatically.
This might be the best reason for putting your using directives inside the namespace declaration, regardless of (borderline) technical (borderline) merits mentioned elsewhere; It's as simple as that.
Already mentioned but perhaps better illustrated:
Placing using directives inside the namespace avoids unnecessary repetition and makes our declarations more terse.
This is unnecessarily terse:
using Com.Acme.Products.Traps.RoadRunnerTraps;
namespace Com.Acme.Products.Traps {
This is sweet and to the point:
namespace Com.Acme.Products.Traps {
using RoadRunnerTraps;
As a rule, external using directives (System and Microsoft namespaces for example) should be placed outside the namespace directive. They are defaults that should be applied in all cases unless otherwise specified. This should include any of your own organization's internal libraries that are not part of the current project, or using directives that reference other primary namespaces in the same project. Any using directives that reference other modules in the current project and namespace should be placed inside the namespace directive. This serves two specific functions:
It provides a visual distinction between local modules and 'other' modules, meaning everything else.
It scopes the local directives to be applied preferentially over global directives.
The latter reason is significant. It means that it's harder to introduce an ambiguous reference issue that can be introduced by a change no more significant than refactoring code. That is to say, you move a method from one file to another and suddenly a bug shows up that wasn't there before. Colloquially, a 'heisenbug' - historically fiendishly difficult to track down.
It is a better practice if those default using i.e. "references" used in your source solution should be outside the namespaces and those that are "new added reference" is a good practice is you should put it inside the namespace. This is to distinguish what references are being added.
I have been running StyleCop over some C# code, and it keeps reporting that my using directives should be inside the namespace.
Is there a technical reason for putting the using directives inside instead of outside the namespace?
There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:
// File1.cs
using System;
namespace Outer.Inner
{
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
Now imagine that someone adds another file (File2.cs) to the project that looks like this:
// File2.cs
namespace Outer
{
class Math
{
}
}
The compiler searches Outer before looking at those using directives outside the namespace, so it finds Outer.Math instead of System.Math. Unfortunately (or perhaps fortunately?), Outer.Math has no PI member, so File1 is now broken.
This changes if you put the using inside your namespace declaration, as follows:
// File1b.cs
namespace Outer.Inner
{
using System;
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
Now the compiler searches System before searching Outer, finds System.Math, and all is well.
Some would argue that Math might be a bad name for a user-defined class, since there's already one in System; the point here is just that there is a difference, and it affects the maintainability of your code.
It's also interesting to note what happens if Foo is in namespace Outer, rather than Outer.Inner. In that case, adding Outer.Math in File2 breaks File1 regardless of where the using goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any using directive.
This thread already has some great answers, but I feel I can bring a little more detail with this additional answer.
First, remember that a namespace declaration with periods, like:
namespace MyCorp.TheProduct.SomeModule.Utilities
{
...
}
is entirely equivalent to:
namespace MyCorp
{
namespace TheProduct
{
namespace SomeModule
{
namespace Utilities
{
...
}
}
}
}
If you wanted to, you could put using directives on all of these levels. (Of course, we want to have usings in only one place, but it would be legal according to the language.)
The rule for resolving which type is implied, can be loosely stated like this: First search the inner-most "scope" for a match, if nothing is found there go out one level to the next scope and search there, and so on, until a match is found. If at some level more than one match is found, if one of the types are from the current assembly, pick that one and issue a compiler warning. Otherwise, give up (compile-time error).
Now, let's be explicit about what this means in a concrete example with the two major conventions.
(1) With usings outside:
using System;
using System.Collections.Generic;
using System.Linq;
//using MyCorp.TheProduct; <-- uncommenting this would change nothing
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
namespace MyCorp.TheProduct.SomeModule.Utilities
{
class C
{
Ambiguous a;
}
}
In the above case, to find out what type Ambiguous is, the search goes in this order:
Nested types inside C (including inherited nested types)
Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
Types in namespace MyCorp.TheProduct.SomeModule
Types in MyCorp.TheProduct
Types in MyCorp
Types in the null namespace (the global namespace)
Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty
The other convention:
(2) With usings inside:
namespace MyCorp.TheProduct.SomeModule.Utilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct; // MyCorp can be left out; this using is NOT redundant
using MyCorp.TheProduct.OtherModule; // MyCorp.TheProduct can be left out
using MyCorp.TheProduct.OtherModule.Integration; // MyCorp.TheProduct can be left out
using ThirdParty;
class C
{
Ambiguous a;
}
}
Now, search for the type Ambiguous goes in this order:
Nested types inside C (including inherited nested types)
Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty
Types in namespace MyCorp.TheProduct.SomeModule
Types in MyCorp
Types in the null namespace (the global namespace)
(Note that MyCorp.TheProduct was a part of "3." and was therefore not needed between "4." and "5.".)
Concluding remarks
No matter if you put the usings inside or outside the namespace declaration, there's always the possibility that someone later adds a new type with identical name to one of the namespaces which have higher priority.
Also, if a nested namespace has the same name as a type, it can cause problems.
It is always dangerous to move the usings from one location to another because the search hierarchy changes, and another type may be found. Therefore, choose one convention and stick to it, so that you won't have to ever move usings.
Visual Studio's templates, by default, put the usings outside of the namespace (for example if you make VS generate a new class in a new file).
One (tiny) advantage of having usings outside is that you can then utilize the using directives for a global attribute, for example [assembly: ComVisible(false)] instead of [assembly: System.Runtime.InteropServices.ComVisible(false)].
Update about file-scoped namespace declarations
Since C# 10.0 (from 2021), you can avoid indentation and use either (convention 1, usings outside):
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
namespace MyCorp.TheProduct.SomeModule.Utilities;
class C
{
Ambiguous a;
}
or (convention 2, usings inside):
namespace MyCorp.TheProduct.SomeModule.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using MyCorp.TheProduct;
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;
class C
{
Ambiguous a;
}
But the same considerations as before apply.
Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make much of a difference whether they go outside or inside the namespace.
using ThisNamespace.IsImported.InAllNamespaces.Here;
namespace Namespace1
{
using ThisNamespace.IsImported.InNamespace1.AndNamespace2;
namespace Namespace2
{
using ThisNamespace.IsImported.InJustNamespace2;
}
}
namespace Namespace3
{
using ThisNamespace.IsImported.InJustNamespace3;
}
According to Hanselman - Using Directive and Assembly Loading... and other such articles there is technically no difference.
My preference is to put them outside of namespaces.
According the to StyleCop Documentation:
SA1200: UsingDirectivesMustBePlacedWithinNamespace
Cause
A C# using directive is placed outside of a namespace element.
Rule Description
A violation of this rule occurs when a using directive or a using-alias directive is placed outside of a namespace element, unless the file does not contain any namespace elements.
For example, the following code would result in two violations of this rule.
using System;
using Guid = System.Guid;
namespace Microsoft.Sample
{
public class Program
{
}
}
The following code, however, would not result in any violations of this rule:
namespace Microsoft.Sample
{
using System;
using Guid = System.Guid;
public class Program
{
}
}
This code will compile cleanly, without any compiler errors. However, it is unclear which version of the Guid type is being allocated. If the using directive is moved inside of the namespace, as shown below, a compiler error will occur:
namespace Microsoft.Sample
{
using Guid = System.Guid;
public class Guid
{
public Guid(string s)
{
}
}
public class Program
{
public static void Main(string[] args)
{
Guid g = new Guid("hello");
}
}
}
The code fails on the following compiler error, found on the line containing Guid g = new Guid("hello");
CS0576: Namespace 'Microsoft.Sample' contains a definition conflicting with alias 'Guid'
The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code.
When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error.
Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose.
Placing using-alias directives within the namespace element eliminates this as a source of bugs.
Multiple Namespaces
Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.
It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.
How to Fix Violations
To fix a violation of this rule, move all using directives and using-alias directives within the namespace element.
There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier using statements and has to be fully qualified.
Consider:
namespace MyNamespace
{
using System;
using MyAlias = System.DateTime;
class MyClass
{
}
}
versus:
using System;
namespace MyNamespace
{
using MyAlias = DateTime;
class MyClass
{
}
}
This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):
using MyAlias = Tuple<Expression<Func<DateTime, object>>, Expression<Func<TimeSpan, object>>>;
With using statements inside the namespace, it suddenly becomes:
using MyAlias = System.Tuple<System.Linq.Expressions.Expression<System.Func<System.DateTime, object>>, System.Linq.Expressions.Expression<System.Func<System.TimeSpan, object>>>;
Not pretty.
One wrinkle I ran into (that isn't covered in other answers):
Suppose you have these namespaces:
Something.Other
Parent.Something.Other
When you use using Something.Other outside of a namespace Parent, it refers to the first one (Something.Other).
However if you use it inside of that namespace declaration, it refers to the second one (Parent.Something.Other)!
There is a simple solution: add the "global::" prefix: docs
namespace Parent
{
using global::Something.Other;
// etc
}
Another subtlety that I don't believe has been covered by the other answers is for when you have a class and namespace with the same name.
When you have the import inside the namespace then it will find the class. If the import is outside the namespace then the import will be ignored and the class and namespace have to be fully qualified.
//file1.cs
namespace Foo
{
class Foo
{
}
}
//file2.cs
namespace ConsoleApp3
{
using Foo;
class Program
{
static void Main(string[] args)
{
//This will allow you to use the class
Foo test = new Foo();
}
}
}
//file3.cs
using Foo; //Unused and redundant
namespace Bar
{
class Bar
{
Bar()
{
Foo.Foo test = new Foo.Foo();
Foo test = new Foo(); //will give you an error that a namespace is being used like a class.
}
}
}
As Jeppe Stig Nielsen said, this thread already has great answers, but I thought this rather obvious subtlety was worth mentioning too.
using directives specified inside namespaces can make for shorter code since they don't need to be fully qualified as when they're specified on the outside.
The following example works because the types Foo and Bar are both in the same global namespace, Outer.
Presume the code file Foo.cs:
namespace Outer.Inner
{
class Foo { }
}
And Bar.cs:
namespace Outer
{
using Outer.Inner;
class Bar
{
public Foo foo;
}
}
That may omit the outer namespace in the using directive, for short:
namespace Outer
{
using Inner;
class Bar
{
public Foo foo;
}
}
The technical reasons are discussed in the answers and I think that it comes to the personal preferences in the end since the difference is not that big and there are tradeoffs for both of them. Visual Studio's default template for creating .cs files use using directives outside of namespaces e.g.
One can adjust stylecop to check using directives outside of namespaces through adding stylecop.json file in the root of the project file with the following:
{
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"orderingRules": {
"usingDirectivesPlacement": "outsideNamespace"
}
}
}
You can create this config file in solution level and add it to your projects as 'Existing Link File' to share the config across all of your projects too.
Not already mentioned:
Placing the using directives inside the namespace declaration is an application of the well-known best programming practice of declaring everything in the smallest scope possible.
If best programming practices are second nature to you, then you do things like that automatically.
This might be the best reason for putting your using directives inside the namespace declaration, regardless of (borderline) technical (borderline) merits mentioned elsewhere; It's as simple as that.
Already mentioned but perhaps better illustrated:
Placing using directives inside the namespace avoids unnecessary repetition and makes our declarations more terse.
This is unnecessarily terse:
using Com.Acme.Products.Traps.RoadRunnerTraps;
namespace Com.Acme.Products.Traps {
This is sweet and to the point:
namespace Com.Acme.Products.Traps {
using RoadRunnerTraps;
As a rule, external using directives (System and Microsoft namespaces for example) should be placed outside the namespace directive. They are defaults that should be applied in all cases unless otherwise specified. This should include any of your own organization's internal libraries that are not part of the current project, or using directives that reference other primary namespaces in the same project. Any using directives that reference other modules in the current project and namespace should be placed inside the namespace directive. This serves two specific functions:
It provides a visual distinction between local modules and 'other' modules, meaning everything else.
It scopes the local directives to be applied preferentially over global directives.
The latter reason is significant. It means that it's harder to introduce an ambiguous reference issue that can be introduced by a change no more significant than refactoring code. That is to say, you move a method from one file to another and suddenly a bug shows up that wasn't there before. Colloquially, a 'heisenbug' - historically fiendishly difficult to track down.
It is a better practice if those default using i.e. "references" used in your source solution should be outside the namespaces and those that are "new added reference" is a good practice is you should put it inside the namespace. This is to distinguish what references are being added.