Using Namespaces (C# Programming Guide)

Namespaces are heavily used within C# programs in two ways. Firstly, the .NET Framework classes use namespaces to organize its many classes. Secondly, declaring your own namespaces can help control the scope of class and method names in larger programming projects.

Accessing Namespaces

Most C# applications begin with a section of using directives. This section lists the namespaces that the application will be using frequently, and saves the programmer from specifying a fully qualified name every time a method contained within is used.

Namespace Aliases

The using Directive (C# Reference) can also be used to create an alias for a namespace. For example, if you are using a previously written namespace that contains nested namespaces, you might want to declare an alias to provide a shorthand way of referencing one in particular, like this:

using Co = Company.Proj.Nested; // define an alias to represent a namespace

Using Namespaces to control scope

The namespace keyword is used to declare a scope. The ability to create scopes within your project helps organize code and provides a way to create globally-unique types. In the following example, a class entitled SampleClass is defined in two namespaces, one nested inside the other. The . Operator (C# Reference) is used to differentiate which method gets called.

Fully Qualified Names

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.

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 twice in this code. However, the fully qualified names are unique. The first one is declared inside C1; thus, its fully qualified name is: N1.C1.C2.The second is declared inside a namespace N2; thus, its fully qualified name is N1.N2.C2.

Using the preceding code segment, you can add a new class member, C3, to the namespace N1.N2 as follows:

Keep in mind 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 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:

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.