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?
.netc++code-organizationnamespacesstylecop
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?
Best Answer
There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:
Now imagine that someone adds another file (File2.cs) to the project that looks like this:
The compiler searches
Outer
before looking at thoseusing
directives outside the namespace, so it findsOuter.Math
instead ofSystem.Math
. Unfortunately (or perhaps fortunately?),Outer.Math
has noPI
member, so File1 is now broken.This changes if you put the
using
inside your namespace declaration, as follows:Now the compiler searches
System
before searchingOuter
, findsSystem.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 inSystem
; 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 namespaceOuter
, rather thanOuter.Inner
. In that case, addingOuter.Math
in File2 breaks File1 regardless of where theusing
goes. This implies that the compiler searches the innermost enclosing namespace before it looks at anyusing
directive.