Creating Type Aliases in C#
The using directive of the C# programming language is often used to create namespace aliases, allowing types with matching names that appear in separate namespaces to be easily accessed. A lesser known use of the directive is to create aliases for types.
In a previous article describing namespaces I described the use of the using directive. The using directive allows you to identify a namespace that contains types that are used within the code file. When you access types in that namespace, you don't need to provide a fully qualified name. Occasionally you will find that you wish to use classes from two separate namespaces where the types have the same name. In these situations you can either use the fully qualified name for at least one of those types or you can create aliases for the namespaces.
In addition to creating aliases for namespaces, you can also add aliases for individual types. This allows you to disambiguate type names without referencing an entire namespace. Again, the using directive adds the alias for the scope of the file in which it appears. You cannot use a using directive to create global aliases that work across your projects or solutions.
The syntax for creating type aliases is similar to that for namespace aliases. The using keyword is followed by the alias, an equals sign and the fully qualified name of the type to be aliased. The following creates an alias for the StringBuilder class:
using SB = System.Text.StringBuilder;
With the alias in place, you can use it as if it were the true name of the class. For example, the following code creates a new StringBuilder and initialises it using a constructor, also referred to using the alias.
SB stringBuilder = new SB("InitialValue");
Generic Type Aliases
You can also create aliases for generic classes, as long as your provide specific types for the type parameters. The code sample creates an alias for the Nullable structure that will hold nullable DateTime values:
using NullableDateTime = System.Nullable<System.DateTime>;
We can now use the alias without requiring a type parameter:
NullableDateTime ndt = (NullableDateTime)DateTime.Now;
When you create an alias for a generic type, you cannot leave the type open. All of the type parameters must be resolved within the using directive. The following code breaks this rule by attempting to create an alias with a changeable type parameter. As such, it will not compile.
using NullableThing<T> = System.Nullable<T>;
15 May 2012