.NET: How to Alias Namespaces and Data Types (C# and Visual Basic .NET)
One of the little known features of .NET is that you can give complete namespaces and data types alias’s that you can reference them with in code.
Aliasing Data Types
For this example we’ll give a different name to the integer data type:
Imports MyInteger = System.Int32;
using MyInteger = System.Int32;
Now to use the alias in code:
Public myVariable As MyInteger = 4;
MyInteger myVariable = 4;
For this example, lets assume we want to use an alias to rename the System namespace to Sys to its easier to type.
Imports Sys = System;
using Sys = System;
With the above alias in place, you can change this:
System.Int32 myInt = 4;
Sys.Int32 myInt = 4;
A good use of aliasing would be when you are working on a large project and you are dependant on another developer to finish their class or namespace before you can complete a piece of your code. You can create “dummy” or stub objects and namespaces of your own and them give them an alias that is what the actual name will be when the other developer is finished. Then when they’re finished, you can just take out your alias’s and include their namespaces and everything will work fine. This trick allows you to still keep coding and successfully compiling without exceptions caused by the namespaces or objects not existing.
Another good use of aliasing would be if you are using Int32 in your code now, but you want to make it easier to switch to Double or Int64. Using aliasing allows you to change one line of code to change the data type that is being used.
The last usage tip and probably the best one, is to use aliasing to eliminate the confusion of Ambiguous data types when using multiple namespaces each having objects with the same name. This way you wont have to type out the entire namespace when using the ambiguous objects.