3

I have a generic class in C#, like this:

   public class GenericClass<T> { ... }

Now, I have the Type object for an object, and would like to, through reflection or otherwise, to get the Type object for GenericClass<T> where T corresponds to that Type object I have my object.

Like this:

   Type requiredT = myobject.GetType();
   Type wantedType = typeof(GenericClass<requiredT>);

Obviously this syntax doesn't work, but how do I do it?

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
Toto
  • 7,491
  • 18
  • 50
  • 72

3 Answers3

9

Yes, you can:

Type requiredT = ...
Type genericType = typeof(GenericClass<>);
Type wantedType = genericType.MakeGenericType(requiredT);

This will give you the GenericClass<T> Type object, where T corresponds to your requiredT.

You can then construct an instance using Activator, like this:

var instance = Activator.CreateInstance(wantedType, new Object[] { ...params });
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
5
Type requiredT = myobject.GetType();
Type genericType = typeof(GenericClass<>);
Type wantedType = genericType.MakeGenericType(requiredT);
BFree
  • 102,548
  • 21
  • 159
  • 201
5
Type wantedType = typeof(GenericClass<>).MakeGenericType(requiredT);
LukeH
  • 263,068
  • 57
  • 365
  • 409