In this post, we will explore a way to call a C# generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime.
Calling a C# Generic Method using Reflection
Consider the following C# sample code - inside the InitializeOrder() method, what's the most suitable way to invoke GenericOrderMethod<T>() using the Type stored in the dynamicType variable?
using System.Reflection;
public class Order
{
public void InitializeOrder(string typeName)
{
Type dynamicType = Type.GetType(typeName);
// How should we call GenericOrderMethod<T>()?
GenericOrderMethod<dynamicType>(); // This won't work
// How should we call StaticOrderMethod<T>()?
Sample.StaticorderMethod<dynamicType>(); // This also won't work
}
public void GenericOrderMethod<T>()
{
// ...
}
public static void StaticOrderMethod<T>()
{
//...
}
}
We need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod.
The MakeGenericMethod method allows you to write code that assigns specific types to the type parameters of a generic method definition, thus creating a MethodInfo object that represents a particular constructed method. If the ContainsGenericParameters property of this MethodInfo object returns true, you can use it to invoke the method or to create a delegate to invoke the method.
Methods constructed with the MakeGenericMethod method can be open, that is, some of their type arguments can be type parameters of enclosing generic types. You might use such open constructed methods when you generate dynamic assemblies. Here is how to use MakeGenericMethod to invoke a generic method in C#:
MethodInfo method = typeof(Order).GetMethod(nameof(Order.GenericOrderMethod));
MethodInfo generic = method.MakeGenericMethod(dynamicType);
generic.Invoke(this, null);
For a static method, pass null as the first argument to Invoke the method. It is good to note that we can achieve the same result if we use type inference in C#.