Get a generic method and invoke it

suggest change

Let’s say you have class with generic methods. And you need to call its functions with reflection.

public class Sample
    public void GenericMethod<T>()
        // ...

    public static void StaticMethod<T>()

Let’s say we want to call the GenericMethod with type string.

Sample sample = new Sample();//or you can get an instance via reflection

MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(typeof(string));
generic.Invoke(sample, null);//Since there are no arguments, we are passing null

For the static method you do not need an instance. Therefore the first argument will also be null.

MethodInfo method = typeof(Sample).GetMethod("StaticMethod");
MethodInfo generic = method.MakeGenericMethod(typeof(string));
generic.Invoke(null, null);

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents