21

I need to create a generic type, but I do not know the type at compile time. I would like to do this:

Type t = typeof(whatever);
var list = new List<t>

this won't compile, because t is not a valid type. But it does know all about a valid type. Is there a way to dynamically create the generic list from a System.Type like this? I may need reflection, and that's ok, I am just a bit lost here.

captncraig
  • 22,118
  • 17
  • 108
  • 151

1 Answers1

28

Like this:

Type t;
Type genericListType = typeof(List<>).MakeGenericType(t);
object list = Activator.CreateInstance(genericListType);

Note that you can only assign it to a variable of type object. (Although you can cast to to the non-generic IList interface)

To use the list variable, you'll probably need reflection.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • This works great, except it is a pain to use afterward. Gets the job done though. – captncraig May 14 '10 at 14:49
  • Correct; it's a pain to use. There may be better options; you can ask another question here and tell us what you're trying to do. – SLaks May 14 '10 at 14:57
  • Turns out in my application of this, I can quite easily cast it to a nongeneric interface and it works quite well. – captncraig Jun 03 '10 at 17:53