Namespaces and types have unique titles described by fully qualified names that indicate a logical hierarchy. For example, the statement A.B implies that A is the name of the namespace or type, and B is nested inside it.
In the following example, there are nested classes and namespaces. The fully qualified name is indicated as a comment following each entity.
namespace N1 // N1
{
class C1 // N1.C1
{
class C2 // N1.C1.C2
{
}
}
namespace N2 // N1.N2
{
class C2 // N1.N2.C2
{
}
}
}
In the previous code segment:
The namespace N1 is a member of the global namespace. Its fully qualified name is N1.
The namespace N2 is a member of N1. Its fully qualified name is N1.N2.
The class C1 is a member of N1. Its fully qualified name is N1.C1.
The class name C2 is used two times in this code. However, the fully qualified names are unique. The first instance of C2 is declared inside C1; therefore, its fully qualified name is: N1.C1.C2. The second instance of C2 is declared inside a namespace N2; therefore, its fully qualified name is N1.N2.C2.
Using the previous code segment, you can add a new class member, C3, to the namespace N1.N2 as follows:
namespace N1.N2
{
class C3 // N1.N2.C3
{
}
}
In general, use :: to reference a namespace alias or global:: to reference the global namespace and . to qualify types or members.
It is an error to use :: with an alias that references a type instead of a namespace. For example:
using Alias = System.Console;
class TestClass
{
static void Main()
{
// Error
//Alias::WriteLine("Hi");
// OK
Alias.WriteLine("Hi");
}
}
Remember that the word global is not a predefined alias; therefore, global.X does not have any special meaning. It acquires a special meaning only when it is used with ::.
A warning (see Compiler Warning (level 2) CS0440) is generated if you define an alias named global because global:: always references the global namespace and not an alias. For example, the following line generates the warning:
using global = System.Collections; // Warning
Using :: with aliases is a good idea and protects against the unexpected introduction of additional types. For example, consider this example:
namespace Library
{
public class C : Alias.Exception { }
}
This works, but if a type named Alias were to subsequently be introduced, Alias. would bind to that type instead. Using Alias::Exception insures that Alias is treated as a namespace alias and not mistaken for a type.
See the topic How to: Use the Namespace Alias Qualifier (C# Programming Guide) for more information regarding the global alias.