tags:

views:

185

answers:

1

If I had generic class:

public class GenericTest<T> : IGenericTest {...}

and I had an instance of Type, which I got through reflection, how could I instantiate GenericType with that Type? For example:

public IGenericTest CreateGenericTestFromType(Type tClass)
{
   return (IGenericTest)(new GenericTest<tClass>());
}

Of course, the above method won't compile, but it illustrates what I'm trying to do.

+6  A: 

You need to use Type.MakeGenericType:

public IGenericTest CreateGenericTestFromType(Type tClass)
{
   Type type = typeof(GenericTest<>).MakeGenericType(new Type[] { tClass });
   return (IGenericTest) Activator.CreateInstance(type);
}
Jon Skeet
Thanks! Perfect answer.
Jeremy