What is the difference between
namespace x
{
using y;
}
and
using y;
namespace x
{
}
?
What is the difference between
namespace x
{
using y;
}
and
using y;
namespace x
{
}
?
The first one has y in scope for just the namespace x, the second has y in scope for the whole file, so potentialy other namespaces. If you keep to one namespace per file (I'd guess that was the convention) then there's usually no real difference [but see Marc's comment about clashes if different types have the same name in different namespaces]. If you use StyleCop it will want you to keep the usings inside the namespace.
Putting the using
statement inside the namespace
block scopes it to that block. This affects a number of things.
using
statement is only valid within the block, so if there were other namespace
blocks, they wouldn't be affected.using
can be shortened based on the outer namespace
block. So using x.y;
outside of the namespace can just be expressed as using y;
inside of the namespace x
block.using
inside of the namespace causes the compiler to guarantee that the specified namespace isn't overwritten. For example:
using Guid = System.Guid;
namespace Sample
{
public class Guid {}
public class Program
{
public static void Main()
{
Console.WriteLine(new Guid());
}
}
}
The above code will compile, but it is unclear which Guid
is being instantiated. If the using
statement is inside of the namespace
block, however, a compiler error is thrown.See the related StyleCop documentation for a more complete discussion.