Lets say I have the following class
public class MyClass<T>
{
public Method(T input)
{
//performs logic with input
}
}
I would like to store the MyClass type in a value like
Type classType = typeof(MyClass);
But since MyClass is a generic class, I cannot perform that operation without declaring a generic like typeof(MyClass<AnotherClass>)
.
Is there a way to make this work?
I wrote somethig like
private void PerformLogic(Type inputType)
{
MethodInfo getTypeMethod = typeof(this).GetMethod("GetType");
getTypeMethod = getTypeMethod.MakeGenericMethod(inputType);
Type result = (Type)getTypeMethod.Invoke(default, default);
// ...
}
private static Type GetType<T>()
where T : class
{
Type type = typeof(MyClass<T>);
return type;
}
But I feel like there is a cleaner way to do this without creating an extra method with "0 references"
At "performs logic with input", you can write:
typeof(T)
to examine the type information of the type argumentT
typeof(MyClass<>)
to examine theMyClass<>
type as a generic type definitiontypeof(MyClass<T>)
to examine the closed generic type ofMyClass<T>
.