Posts Tagged ‘ C ’

How to create a generic list using reflection

Reflection is a very powerful feature which allows you to do lots of crazy things.
But sometimes you want to create a generic class which can be really annoying if you dont know how to do it.

If you try to do it as usual then you will receive an exception.
An example would be

var myType = typeof (double);
var list = (List<myType>) Activator.CreateInstance(typeof (List<myType>), null);

The compiler tells you that a type or namespace is expected and not myType!


In order to do that you can use the MakeGenericType method to add the generic types to the List and after that you can create the instance

var myGenericType = typeof(List<>).MakeGenericType(new []{typeof(double)});
var myList = (List<double>)Activator.CreateInstance(myGenericType);

Note that the MakeGenericType method only creates the type which then is used to create an object in the next line