Jeremy
Jeremy

Reputation: 46322

Creating a generic based on class Type

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.

Upvotes: 4

Views: 358

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

You need to use Type.MakeGenericType:

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

Upvotes: 8

Related Questions