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
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.
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.
Given a type, you can instantiate a new instance this way:
var obj = Activator.CreateInstance(type);
Ref: http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
Something like this:
Activator.CreateInstance(typeof(List<>).MakeGenericType(type))