Tuesday 19 November 2013

How to create a Generic Type Alias?

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.

NOTE: 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.

Generic Type Aliases

You can create aliases for generic classes, as long as your provide specific types for the type parameters.

Example
using Foo = System.Collections.Generic.KeyValuePair<int, string>;

class Sample { Foo x; }

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.

Below code will not compile.
using Foo = System.Collections.Generic.KeyValuePair<T, K>

Type Aliases

Following code creates an alias for the StringBuilder class

using SB = System.Text.StringBuilder;

// Then you can create an instance of StringBuilder using below statement.

SB stringBuilder = new SB();

Useful links>>

using Directive - MSDN

Type Aliases

No comments:

Post a Comment