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;
Usage #1: 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 comlete 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.
**Usage #2: **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.
Usage #3: 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.
This blog post is licensed under the Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the blog post content. All other content on this website is not licensed under Creative Commons licensing.