ECMA-334 C# Language Specification16.3.2: Using namespace directives |
A using-namespace-directive
imports the types contained in a namespace into the immediately enclosing compilation unit or namespace body, enabling the identifier of each type to be used without qualification.
namespace-name
;
Within member declarations in a compilation unit or namespace body that contains a using-namespace-directive
, the types contained in the given namespace can be referenced directly. namespace N1.N2
{
class A {}
}
namespace N3
{
using N1.N2;
class B: A {}
}
A using-namespace-directive
imports the types contained in the given namespace, but specifically does not import nested namespaces.
the namespace N1.N2
{
class A {}
}
namespace N3
{
using N1;
class B: N2.A {} // Error, N2 unknown
}
using-namespace-directive
imports the types contained in N1, but not the namespaces nested in N1. Thus, the reference to N2.A in the declaration of B results in a compile-time error because no members named N2 are in scope. end example]
Unlike a using-alias-directive
, a using-namespace-directive
may import types whose identifiers are already defined within the enclosing compilation unit or namespace body. In effect, names imported by a using-namespace-directive
are hidden by similarly named members in the enclosing compilation unit or namespace body. namespace N1.N2
{
class A {}
class B {}
}
namespace N3
{
using N1.N2;
class A {}
}
When more than one namespace imported by using-namespace-directive
s in the same compilation unit or namespace body contain types by the same name, references to that name are considered ambiguous.
both N1 and N2 contain a member A, and because N3 imports both, referencing A in N3 is a compile-time error. end example]namespace N1
{
class A {}
}
namespace N2
{
class A {}
}
namespace N3
{
using N1;
using N2;
class B: A {} // Error, A is ambiguous
}
using-alias-directive
that picks a particular A.
end example]namespace N3
{
using N1;
using N2;
using A = N1.A;
class B: A {} // A means N1.A
}
Like a using-alias-directive
, a using-namespace-directive
does not contribute any new members to the underlying declaration space of the compilation unit or namespace, but, rather, affects only the compilation unit or namespace body in which it appears.
The namespace-name
referenced by a using-namespace-directive
is resolved in the same way as the namespace-or-type-name
referenced by a using-alias-directive
. Thus, using-namespace-directive
s in the same compilation unit or namespace body do not affect each other and can be written in any order.