← All articles

Namespace Aliasing – The using directive

How to alias a C# namespace or a class with the using directive -- handy when two libraries share a namespace or a type name is painfully long.

Donn Felker

Donn Felker

2007.02.22 · 1 min read

You can easliy alias a namespace in .NET by doing the following:

using System;
using System.Text;
using myXml = System.Xml; // <– myXml is the alias.

Then in the code you can reference it like this:

using System;
using System.Text;
using myXml = System.Xml;

namespace MetaDatdaGenerator
{
   class Program
   {
      static void Main(string[] args)
      {
         myXml.XmlDocument xmlDoc = new myXml.XmlDocument(); 
         // Do stuff
      }
   }
}

Uses

Perhaps you’ve named something with similar namespaces or you’ve encountered a product with a similar namespace. This will allow you to alias them in your projects.

Aliasing a class

You can also alias a class, to save on typing. Saved keystrokes = mo time. Mo time = mo money. Mo money = mo problems! Oh, wait, nevermind…anyway… here’s the code.

using System;
using System.Text;
using myXml = System.Xml;
using myException = ExampleCompany.ExampleProduct.Common.Exception.SomeExceptionWithAReallyReallyLongName;

namespace ExampleCompany.ExampleProduct
{
   class Program
   {
      static void Main(string[] args)
      {
         if (args.Length == 0)
         {
            throw new myException(“Please provide a parameter!”); 
         }
      }
   }
}

Conclusion

Though it may not be used often, I’ve found myself using it a couple times when I needed to resolve some names to save on typing as well as an instance where I had two classes with the same name.

MSDN link: The using directive.

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading