C# Using Alias Example

Using keyword

You want to be able to specify what a certain type name points to in your C# program. With a using alias directive, you can introduce new type names that point to any existing type or namespace. This provides a bit more flexibility should the implementation need to change.

This C# article describes how to use the using alias feature.

Alias example

Note

The using alias directive syntax requires the "using" keyword and then the equals sign. Then, an existing type name or namespace is required. Here, we map the type "Cat" to the type "System.Text.StringBuilder". In the program, then, the type Cat can be used as a StringBuilder.

Program that shows using alias directive [C#]

using System;
using Cat = System.Text.StringBuilder;

class Program
{
    static void Main()
    {
	Cat cat = new Cat();
	cat.Append("sparky");
	cat.Append(100);

	Console.WriteLine(cat);
    }
}

Output

sparky100

Drawback. This can be used to create extremely confusing and non-standard programs. If you want to create extremely confusing programs, just don't put that on your resume if you are looking for employment.

Practical use

Question and answer

What are some practical uses of the using alias directive? Sometimes, an entire program would want to use one type implementation for DEBUG mode, and a different implementation for RELEASE mode. You could have the program use an alias instead of the actual type names. Then, you could use #ifdef and #else to wrap the using alias directive.

This directive can also resolve ambiguities in programs. Say for example that you have a custom StringBuilder type in the namespace Perls.Animals.StringBuilder. If you include both System.Text and this other namespace, the using alias directive can be used to specify what StringBuilder actually points to.

Summary

The C# programming language

As with the extern alias directive, the using alias directive is used to resolve ambiguities in programs. It can also enable you to swap implementations for a type based on compile-time flags. The major drawback is that it can be abused to create programs that are extremely confusing.

Visual Studio Tips
.NET