Get generic type of class at runtime
If you want to get the generic type of a class at runtime, you can use the Type
class in the System
namespace. For example, if you have a class MyClass<T>
, you can use the following code to get the type of T
at runtime:
Type classType = typeof(MyClass<>);
Type genericType = classType.GetGenericArguments()[0];
The GetGenericArguments
method returns an array of Type
objects representing the type arguments of the current generic type. In this case, there is only one type argument, so we can get it by indexing the array with 0.
Keep in mind that this will only work if the class is a generic type. If the class is not generic, the GetGenericArguments
method will return an empty array.
I hope this helps! Let me know if you have any other questions.