First I'd like to say Happy New Year! I hope that everyone had a good time celebrating NYE 2017. Now let's move onto the fun stuff in 2018, programming! I have been seeing a lot of questions about how to call generic methods using reflection in C# so that will be the topic at focus.
Calling generic methods in C# is generally straight forward but as with anything it get can difficult. Consider a scenario where you are trying to call a generic method when the type parameter isn't known at compile time. How would you execute the method?
Sample class
public class Sample { public void Example(string typeName) { Type myType = FindType(typeName); // This is where the example code shown below would be executed } public void GenericMethod() { // Do Stuff } public static void StaticMethod () { // Do Stuff } }
Calling generic methods using reflection
Instantiate the method using MakeGenericMethod
First get the GenericMethod() by name, then instantiate the method using MakeGenericMethod. Note that if you are instantiating a static method you may need to specify the binding flags when calling GetMethod(). For example, passing BindingFlags.Static will return a static method.
MethodInfo method = typeof(Sample).GetMethod("GenericMethod"); MethodInfo generic = method.MakeGenericMethod(myType);
Invoking a generic method using reflection
Execute GenericMethod() using reflection. Note that passing "this" in this context is the equivalent of passing "new Sample()".
generic.Invoke(this, null);
Invoking a static generic method using reflection
Invoking a static generic method is similar to a non-static generic method. Just remember to pass null as the first argument when we call .Invoke().
generic.Invoke(null, null);