Dynamic build of generics types at runtime

How to create dynamically a type in .Net when it’s only known a string representation of that type, I think it’s an operation known to almost all .Net programmers, but what happened with types with type parameters (or generics) ?

In .Net is possible to create dynamically both generics with a known type, i.e. List<>, and generics with type in turn dynamically built.

Here’s an example:

a) Dynamic generated both type parameter and type

Type collectionType = Type.GetType("System.Collections.Generic.List`1, mscorlib");
if (collectionType == "null")
    throw new InvalidOperationException("Invalid type");
Type genericType = Type.GetType("MyNamespace.MyType, MyAssembly");
Type listWithGeneric = collectionType.MakeGenericType(genericType);
var myList = Activator.CreateInstance(listWithGeneric) as IList;

b) Dynamic generated type parameter with a known type (System.Collection.Generic.List in this case):

Type genericType = Type.GetType("MyNamespace.MyType, MyAssembly");
Type listWithGeneric = typeof(List<>).MakeGenericType(genericType);
var myList = Activator.CreateInstance(listWithGeneric) as IList;
Technorati Tags: ,,

Leave a Reply

Your email address will not be published. Required fields are marked *