reddy reddy - 2 months ago 9
C# Question

Invoke a generic method with a subtype of the generic parameter type

I am trying to invoke a generic method via reflection using a subtype of the generic parameter type. Here's the situation :

public abstract class MyClass<T> where T : class
{
}

public static class Caller
{
public static void Do<T>(MyClass<T> param1, string param2 = null) where T : class
{

}
}

public class ConcreteClass : MyClass<string>
{

}


However when I try to do :

ConcreteClass instance = Activator.CreateInstance(typeof(ConcreteClass));
MethodInfo methodInfo = typeof(Caller).GetMethod("Do");
methodInfo = methodInfo.MakeGenericMethod(typeof(ConcreteClass));
methodInfo.Invoke(null, new object[] { instance, Type.Missing });


I am getting an exception essentially saying :


Cannot convert type 'ConcreteClass' to type 'MyClass`[ConcreteClass]'


The exception message is very clear, however I don't seem to find how I can achieve what I am after.

Edit:

The compile time equivalent for what I am trying to achieve is :

Caller.Do(new ConcreteClass());


Which compiles fine.

Lee Lee
Answer

ConcreteClass extends MyClass<string> so you need to provide typeof(string) to MakeGenericMethod:

ConcreteClass instance = (ConcreteClass)Activator.CreateInstance(typeof(ConcreteClass));
MethodInfo methodInfo = typeof(Caller).GetMethod("Do");
methodInfo = methodInfo.MakeGenericMethod(typeof(string));
methodInfo.Invoke(null, new object[] { instance, Type.Missing });
Comments