C# Reflections: How to get type of a generic object

1.4k views Asked by At

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"

1

There are 1 answers

0
Julius On

At "performs logic with input", you can write:

  • typeof(T) to examine the type information of the type argument T
  • typeof(MyClass<>) to examine the MyClass<> type as a generic type definition
  • typeof(MyClass<T>) to examine the closed generic type of MyClass<T>.