Team LiB
Previous Section Next Section

Namespaces and the using Keyword

A namespace is used to collect a hierarchy of objects into a single name. Namespaces may span .cs files, but not assemblies. The main purpose of a namespace is to collect and build an object hierarchy that is easy to use and navigate.

The using keyword allows you to use class objects that are deeply nested in namespaces, without needing to use their fully qualified names. For example, suppose that we wanted to access the RemotingConfiguration class. We could do this:

System.Runtime.Remoting.RemotingConfiguration ...

Or we could do this:

using System.Runtime.Remoting;
RemotingConfiguration ...

The using keyword can also be used to control ambiguity. Let's say that we have two assemblies: MyAssembly and YourAssembly. Both assemblies possess a class called Dog. Suppose we do the following:

using MyAssembly;
using YourAssembly;

Now if we tried to use the Dog class, we would get compiler errors. This is because the compiler would not know which class to use, MyAssembly.Dog or YourAssembly.Dog. There are a couple of solutions to this type of problem. The first would be to use fully qualified names: MyAssembly.Dog and YourAssembly.Dog. A quicker route would be to use an alias. C# supports this by using the following syntax:

using MyDog = MyAssembly.Dog;
using YourDog = YourAssembly.Dog;

Team LiB
Previous Section Next Section