Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate List<T> but T is unknown until runtime?

Tags:

c#

Assume I have a class that is unknown until runtime. At runtime I get a reference, x, of type Type referencing to Foo.GetType(). Only by using x and List<>, can I create a list of type Foo?

How to do that?

like image 494
xport Avatar asked Oct 08 '10 07:10

xport


2 Answers

Type x = typeof(Foo);
Type listType = typeof(List<>).MakeGenericType(x);
object list = Activator.CreateInstance(listType);

Of course you shouldn't expect any type safety here as the resulting list is of type object at compile time. Using List<object> would be more practical but still limited type safety because the type of Foo is known only at runtime.

like image 57
Darin Dimitrov Avatar answered Nov 14 '22 01:11

Darin Dimitrov


Sure you can:

var fooList = Activator
    .CreateInstance(typeof(List<>)
    .MakeGenericType(Foo.GetType()));

The Problem here is that fooList is of type object so you still would have to cast it to a "usable" type. But what would this type look like? As a data structure supporting adding and looking up objects of type T List<T> (or rather IList<>) is not covariant in T so you cannot cast a List<Foo> to a List<IFoo> where Foo: IFoo. You could cast it to an IEnumerable<T> which is covariant in T.

If you are using C# 4.0 you could also consider casting fooList to dynamic so you can at least use it as a list (e.g. add, look-up and remove objects).

Considering all this and the fact, that you don't have any compile-time type safety when creating types at runtime anyhow, simply using a List<object> is probably the best/most pragmatic way to go in this case.

like image 11
Frank Avatar answered Nov 13 '22 23:11

Frank