views:

2831

answers:

2

Hello ! i've got a question about how is it possible (if possible :) to use a type reference returned by Type.GetType() to, for example, create IList of that type?

here's sample code :

Type customer = Type.GetType("myapp.Customer");
IList<customer> customerList = new List<customer>(); // got an error here =[

Thank You in Advance !

+11  A: 

Something like this:

Type listType = typeof(List<>).MakeGenericType(customer);
IList customerList = (IList)Activator.CreateInstance(listType);

Of course you can't declare it as

IList<customer>

because it is not defined at compile time. But List<T> implements IList, so you can use this.

Stefan Steinegger
Yes, because it's not defined at compile time, there's not much point in using a generic List<> - you might as well use a non-generic container such as ArrayList.
Groky
Actually you should cast the result of Activator.CreateInstance to IList, since it returns an object...
Thomas Levesque
@Thomas: thanks, fixed it. @Groky: It depends. Using the generic list you get runtime type checks when adding items. Or you need to assign it to a field you know (by some context) that it is of the same type.
Stefan Steinegger
A: 

The solution to your problem is provided by Stefan already.

The reason that you can not do IList<customer> is because you can not mix compile time and run-time types this way. A hint when I try to reason about something like this is: how can intellisense figure out what members it must show. In your example this can only be resolved at runtime.

The answer given by Stefan, can be used. However I think it does not help in your underlying problem, because it does not give you intellisense. So I think you have no advantage over using just a non-generic list.

Ruben
As Stefan pointed out in the comments for his answer there are still advandages, such as the generic list preventing the code from adding objects of different types to the list. You do lose intellisense though.
Fredrik Mörk