Tuesday, June 17, 2008

Using using's class alias declaration

One big annoyance I had for a long time, is that generic types can create such a long and cryptic declaration in your code. But today I discovered a hidden feature of the using declaration that makes coding so much easier.

using is not only useful for importing namespaces. You can use it to declare an alias (shortcut, abbreviaton) for a class name too.

It is very simple, here is an example:

using S = System.String;

If you use the type S in your code, then it will refer to the type System.String. Note that you have to fully qualify the name to the class.

Lets have a look at a more complex declaration:

using ComplexType = System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<int,object>;

With this declaration you save a lot of space in your code. The next example shows this, one statement uses the alias type and the other statement does not:

// Using the using class alias declaration.
ComplexType ct1 = new ComplexType();

// Using the regular declaration.
Dictionary<string,Dictionary<int,object>> ct2 = new Dictionary<string,Dictionary<int,object>>();


I can guess which one you like. ;-)

However, of course there are some drawbacks. They are the same as namespace import using statements.
  1. The using class alias declaration is only valid in the file where it is declared.
  2. You must specify the using class alias declaration before using it in the code.
Although, I think it is quite easy to overcome these, as you are already familiar using namespace import using statements.

For more information read the MSDN article using Directive (C#).