Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a static method given it's dynamic type and arguments in c#

Tags:

c#

reflection

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" })
like image 335
Ian Davis Avatar asked Mar 11 '26 05:03

Ian Davis


2 Answers

You're looking for the MakeGenericMethod method of MethodInfo:

Type.GetType("MyClass")
    .GetMethod("MyMethod")
    .MakeGenericMethod(typeOfGenericArgument)
    .Invoke(null, new object[] { "student" })
like image 149
Servy Avatar answered Mar 13 '26 19:03

Servy


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" });
like image 40
Selman Genç Avatar answered Mar 13 '26 18:03

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!