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?
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?
Something like this:
Activator.CreateInstance(typeof(List<>).MakeGenericType(type))
Sure you can:
The Problem here is that
fooList
is of typeobject
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 typeT
List<T>
(or ratherIList<>
) is not covariant inT
so you cannot cast aList<Foo>
to aList<IFoo>
whereFoo: IFoo
. You could cast it to anIEnumerable<T>
which is covariant inT
.If you are using C# 4.0 you could also consider casting
fooList
todynamic
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.Given a type, you can instantiate a new instance this way:
Ref: http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
Of course you shouldn't expect any type safety here as the resulting list is of type
object
at compile time. UsingList<object>
would be more practical but still limited type safety because the type ofFoo
is known only at runtime.