How to instantiate List <T> but T is unknown before execution?
Suppose I have a class that is unknown before execution. At run time, I get an x ββreference, of type Type, referencing Foo.GetType (). Only using x and List <>, can I create a list of Foo types?
How to do it?
Type x = typeof(Foo); Type listType = typeof(List<>).MakeGenericType(x); object list = Activator.CreateInstance(listType); Of course, you should not expect any type safety, since the resulting list is of type object at compile time. Using a List<object> would be a more practical, but still limited type of security, since the type Foo is known only at run time.
Of course you can:
var fooList = Activator .CreateInstance(typeof(List<>) .MakeGenericType(Foo.GetType())); The problem here is that fooList is of type object , so you still have to class it as useful. But what would this type look like? Since the data structure that supports the addition and search of objects of type T List<T> (or rather IList<> ) is not covariant in T , so you cannot use a List<Foo> for List<IFoo> where Foo: IFoo . You can apply it to IEnumerable<T> covariant in T
If you are using C # 4.0, you can also consider casting fooList to dynamic so that you can use it as a list (e.g. add, search and delete objects).
Given all of this and the fact that while creating types at runtime you don't have security at compile time, just using List<object> is probably the best / most pragmatic way in this case.
Something like that:
Activator.CreateInstance (TypeOf (List <.>) MakeGenericType (type))
Given the type, you can instantiate a new instance this way:
var obj = Activator.CreateInstance(type); Link: http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx