Toto
Toto

Reputation: 7719

C# get the the type Generic<T> given T

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?

Upvotes: 3

Views: 716

Answers (3)

LukeH
LukeH

Reputation: 269378

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

Upvotes: 5

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391346

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 });

Upvotes: 9

BFree
BFree

Reputation: 103740

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

Upvotes: 5

Related Questions