Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a generic based on class Type

Tags:

c#

generics

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.

like image 234
Jeremy Avatar asked Mar 01 '23 00:03

Jeremy


1 Answers

You need to use Type.MakeGenericType:

public IGenericTest CreateGenericTestFromType(Type tClass)
{
   Type type = typeof(GenericTest<>).MakeGenericType(new Type[] { tClass });
   return (IGenericTest) Activator.CreateInstance(type);
}
like image 85
Jon Skeet Avatar answered Mar 12 '23 07:03

Jon Skeet