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.
- 10 Oct 2020
- 01 Jul 2020
- 06 Apr 2020
- 11 Mar 2020
- 15 Feb 2020
Recent on Build5Nines.com
- 04 Dec 2020
Latest Cloud News: Apple on K8s, IoT, Microsoft Pluton and more! (November 20, 2020 Build5Nines Weekly)20 Nov 2020
Latest Cloud News: .NET 5 Released, Apple Silicon M1 CPU, and more! (November 12, 2020 Build5Nines Weekly)12 Nov 2020
- 11 Nov 2020
Latest Cloud News: Kubernetes, Terraform, Teams Multi-Login and more! (November 5, 2020 Build5Nines Weekly)05 Nov 2020
This site is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. We also participates in affiliate programs with Udemy, and other sites. This site is compensated for referring traffic and business to these companies.