Calling a static method using a Type

Check into the MethodInfo class and the GetMethod() methods on Type.

There are a number of different overloads for different situations.


You need to call MethodInfo.Invoke method:

public class BarClass {
    public void BarMethod(Type t) {
        FooClass.FooMethod(); //works fine
        if (t == typeof(FooClass)) {
            t.GetMethod("FooMethod").Invoke(null, null); // (null, null) means calling static method with no parameters
        }
    }
}

Of course in the above example you might as well call FooClass.FooMethod as there is no point using reflection for that. The following sample makes more sense:

public class BarClass {
    public void BarMethod(Type t, string method) {
        var methodInfo = t.GetMethod(method);
        if (methodInfo != null) {
            methodInfo.Invoke(null, null); // (null, null) means calling static method with no parameters
        }
    }
}

public class Foo1Class {
  static public Foo1Method(){}
}
public class Foo2Class {
  static public Foo2Method(){}
}

//Usage
new BarClass().BarMethod(typeof(Foo1Class), "Foo1Method");
new BarClass().BarMethod(typeof(Foo2Class), "Foo2Method");    

Note, that as 10 years have passed. Personally, I would add extension method:

public static TR Method<TR>(this Type t, string method, object obj = null, params object[] parameters) 
    => (TR)t.GetMethod(method)?.Invoke(obj, parameters);

and then I could call it with:

var result = typeof(Foo1Class).Method<string>(nameof(Foo1Class.Foo1Method));

Tags:

C#