Essential C# Reflection  Suggest an edit

Get a generic method and invoke it

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);

Table Of Contents
22 Enum
25 GUID
62 Reflection
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close