3

I have a class with a static method:

public class MyClass {
    public static bool MyMethod<T>(string arg1) where T : class {
        // ...
    }
}

How can I invoke that given that I know my type for T should be MyNamespace.Data.Models.Student (which is provided via a variable), and the value for arg1 is let's say student.

Is it similar to the following? I'm not sure how to set the T type for it tho.

Type.GetType("MyClass").GetMethod("MyMethod").Invoke(null, new object[] { arg1 = "student" })
Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
Ian Davis
  • 19,091
  • 30
  • 85
  • 133

3 Answers3

4

You're looking for the MakeGenericMethod method of MethodInfo:

Type.GetType("MyClass")
    .GetMethod("MyMethod")
    .MakeGenericMethod(typeOfGenericArgument)
    .Invoke(null, new object[] { "student" })
Servy
  • 202,030
  • 26
  • 332
  • 449
3

First you should get your method and use MakeGenericMethod like this:

 var methodType =Type.GetType("MyClass").GetMethod("MyMethod", BindingFlags.Static |BindingFlags.Public);
 var argumentType = typeof (Student);
 var method = methodType.MakeGenericMethod(argumentType);
 method.Invoke(null, new object[] { "student" });
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

You need to specify BindingFlags.Static in GetMethod to get a static method. Once you've done that, you can make a generic method via MethodInfo.MakeGenericMethod to construct the method with the proper type.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    Unless there is a similarly named instance method making it ambiguous, the `Static` flag isn't needed. – Servy Feb 28 '14 at 21:58