#529 – The using Directive Can Create an Alias for a Namespace

The most common use of the using directive is to bring types within a specified namespace into scope, so that they can be referenced directly in your code.

using DogLibrary;
using DogLibrary.Utility;

You can also use the using directive to create an alias for a namespace, which you can then use to access the types in that namespace.

In the example below, we have two different namespaces that each contain a DogLogger type.  Instead of having to list the fully qualified name of either DogLogger type when we use it, we can assign a shorter alias to refer to the containing namespace.

using U1 = DogLibrary.Utility.StandardLogging;
using U2 = DogLibrary.Utility.AlternateLogging;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            // Short for DogLibrary.Utility.StandardLogging.DogLogger
            U1.DogLogger log1 = new U1.DogLogger(@"C:\log1.txt");

            // Short for DogLibrary.Utility.AlternateLogging.DogLogger
            U2.DogLogger log2 = new U2.DogLogger(@"C:\log2.txt");
        }
    }
}
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: