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.
You need to use Type.MakeGenericType:
public IGenericTest CreateGenericTestFromType(Type tClass)
{
Type type = typeof(GenericTest<>).MakeGenericType(new Type[] { tClass });
return (IGenericTest) Activator.CreateInstance(type);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With