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

I have a general class in C #, for example:

   public class GenericClass<T> { ... }

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

Like this:

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

Obviously this syntax does not work, but how to do it?

+3
source share
3 answers

Yes, you can:

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

This will give you a GenericClass<T>Type object where T matches yours requiredT.

Then you can create an instance using Activator, for example:

var instance = Activator.CreateInstance(wantedType, new Object[] { ...params });
+9
source
Type requiredT = myobject.GetType();
Type genericType = typeof(GenericClass<>);
Type wantedType = genericType.MakeGenericType(requiredT);
+5
source
Type wantedType = typeof(GenericClass<>).MakeGenericType(requiredT);
+5
source

Source: https://habr.com/ru/post/1719612/


All Articles