c# using statements placement [duplicate]
Possible Duplicate:
Should Usings be inside or outside the nam开发者_如何转开发espace
I am looking at a code base where the author (one I respect) consistently places using statements inside of the namespace, as opposed to above it. Is there some advantage (more efficient GC?) to doing so or is this just a code style preference?
Cheers,
BerrylNever put them inside without using "global::" or your code will become brittle.
namspace bar {
using foo //this may mean "using global::bar.foo OR using global::foo"
}
Reference
http://blogs.msdn.com/b/ericlippert/archive/2007/06/25/inside-or-outside.aspx?wa=wsignin1.0
If you have multiple namespaces in the same file then you will be scoping usings only to the containing namespace instead of to all namespace in the entire file.
Also see (just found this good explanation) Should 'using' statements be inside or outside the namespace?
Scott Hanselman did a post about this back in July 2008. I don't know if this changed with the .NET 4 framework, but it basically came down to being a preference issue unless you're naming your classes the same as existing classes as well as multiple namespaces in a single file.
It's a preference thing but there is a semantic difference when you use the statement on the inside versus on the outside in some scenarios.
using Bar;
namespace Foo
{
using Bar;
namespace Bar
{
class C
{
}
}
namespace Baz
{
class D
{
C c = new C();
}
}
}
namespace Bar
{
class E
{
}
}
In this, the outer using statement refers to the namespace Bar that is after namespace Foo. The inner using statement refers to Bar that is inside Foo. If there were no Bar inside Foo, then the inner would also refer to the outer Bar.
Edit And as Jonathan points out, the inner using can be changed to `using global::Bar;" to refer to the out Bar namespace, which would happen to break this particular code because of D trying to use C.
It's MS recommend practice. Programs such as stylecop recommend it.
Check out Is sa1200 All using directives must be placed inside the namespace (StyleCop) purely cosmetic? for a more in-depth discussion
精彩评论