Creating a Generic<T> type instance with a variable containing the Type

Chris picture Chris · Jan 16, 2010 · Viewed 45k times · Source

Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?

Type k = typeof(double);
List<k> lst = new List<k>();

Answer

David M picture David M · Jan 16, 2010

Yes, there is:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);