Encoding closed generic type names as string literals.

19 07 2006

A question came across one of our internal mailing lists today about how to encode closed generic type names as string literals for placement in things like configuration files. This is actually possible, here is an example for a generic list of integers:

System.Collections.Generic.List‘1[[System.Int32]]

Notice the ‘1 notation? That signifies the number of type parameters that follow, so if I had a generic type that took two type parameters (for example a Dictionary<K,V>), then it would be encoded as follows:

System.Collections.Generic.Dictionary‘2[[System.Int32],[System.String]]

In general the best way to find out how to encode type names is to write a quick little console application and get the runtime to tell you the correct notation, for example:

Console.WriteLine(new Dictionary().GetType().FullName);

Once you have the notation right you can instansiate the type as follows:

Type listType = Type.GetType(”System.Collections.Generic.List‘1[[System.Int32]]”);
object listInstance = Activator.CreateInstance(listType);

Easy peasy!