Creating a generic type based on a class type

If I had a general class:

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

and I had an instance of a type that I got through reflection, how can I create an instance of GenericType with this type? For instance:

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

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

+4
source share
1 answer

You need to use Type.MakeGenericType :

 public IGenericTest CreateGenericTestFromType(Type tClass) { Type type = typeof(GenericTest<>).MakeGenericType(new Type[] { tClass }); return (IGenericTest) Activator.CreateInstance(type); } 
+8
source

All Articles