Namespace Aliasing - The using directive

by Donn Felker 22. February 2007 08:11

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.

   

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

Donn Felker

Senior Consultant
MCTS
ScrumMaster
Agile Practitioner

About Me | Books I Recommend

Gotta Pay The Bills


Tag cloud

    Popular Posts

    RecentComments

    Comment RSS

    Calendar

    <<  January 2009  >>
    MoTuWeThFrSaSu
    2930311234
    567891011
    12131415161718
    19202122232425
    2627282930311
    2345678

    View posts in large calendar