Calling a static method using a Type

Viewed 57881

How do I call a static method from a Type, assuming I know the value of the Type variable and the name of the static method?

public class FooClass {
    public static FooMethod() {
        //do something
    }
}

public class BarClass {
    public void BarMethod(Type t) {
        FooClass.FooMethod()          //works fine
        if (t is FooClass) {
            t.FooMethod();            //should call FooClass.FooMethod(); compile error
        }
    }
}

So, given a Type t, the objective is to call FooMethod() on the class that is of Type t. Basically I need to reverse the typeof() operator.

3 Answers

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