Aliasing Data Types in C#

dotnetlogo
One of the secret coding feature in C# is data type aliasing. If you want to use a data type, but think you may need to change to a different data type at some time in the future, define an alias for the data type and use the alias throughout the rest of your code.

Say, for example, that you want to use Int16, but think you may want to change to Int32 later. You could define an alias for Int16.

using ChangeableType = System.Int16;

Anywhere in the code that you want to use that data type, use the alias instead.

ChangeableType m_iSomething=1;
Debug.WriteLine(m_iSomething.GetTypeCode());

If you want to later change to System.Int32, simply change the alias, and then all of the other code will recognize the new type.

using ChangeableType = System.Int32;

A more common use of this technique is in cases where you don’t know the name of the class that you need because another developer is developing that class. You can create a stub for the class, define an alias for the class name, and your application will run. When you get the new class, all you need to do is substitute it in for your stub and change the class name in the alias.

Anky Goyal

I am MCPD certified in .NET and working on .NET technologies for past 3yrs. I am very passionate about the new features which get introduced in the technology. I am here to share the new features i get to know in the world of Microsoft. Follow me on twitter @ankygoyal [email protected]Ankit Goyal

More Posts - Website