In this video, we learn how about dynamically invoking a generic method with reflection in .NET C#.

When using a generic method, the generic argument (often referred to as `T`) must be provided as a known type at compile time. However, sometimes you may have a scenario where you must call a generic method using a type that it not known until run time. This can be problematic and usually results in using a large number of if/else statements.

if (type == typeof(double))
}else if (type == typeof(int))

This code can become quite difficult to maintain as you will have to create an if statement for every object type. What would be better is if you could provide the type at runtime by dynamically invoking a generic method while providing the type.

Luckily, this is quite easy to do with the help of reflection. The first step to dynamically invoking a generic method with reflection is to use reflection to get access to the MethodInfo of the generic method. To do that simply do this:

var methodInfo = typeof(ClassWithGenericMethod).GetMethod("MethodName"); 

Next, we want to create a new MethodInfo using the generic form of the method by using the MakeGenericMethod method.

var genericMethodInfo = methodInfo.MakeGenericMethod(yourRuntimType); 

Finally, you can start dynamically invoking a generic method by using the MethodInfo.Invoke method and passing any parameters the generic method is expecting. For example:

var result = genericMethodInfo.Invoke(null, new object[] { yourArgument }); 

In the above sample, we are providing a `null` value for the object instance as this is a static generic method we are invoking.

And that’s it. That’s how simple it is to start dynamically invoking a generic method with reflection.

Brian Lagunas

View all posts

Follow Me

Follow me on Twitter, subscribe to my YouTube channel, and watch me stream live on Twitch.