How to use reflection to call a generic method in C#

Reflection is a C# feature that enables us to examine and investigate the code at runtime. It offers a way to analyze the metadata of types, methods, properties, fields, and events to dynamically produce and execute instances of objects and types. One common use case of reflection is to call a generic method whose type arguments are not known at compile time. In this Answer, we will explore how to use reflection to call a generic method.

Step to call a generic method using reflections

We can follow these steps to call a generic method using reflection:

  1. Define a generic method.

  2. Get the MethodInfo object for the generic method.

  3. Construct the method generic with the desired type of arguments.

  4. Call the generic method with the specified type of arguments.

Code example

Let’s consider the following playground:

using System;
using System.Reflection;
class Program
{
// Step 1: Define a generic method
public static T Sum<T>(T a, T b)
{
return (dynamic)a + (dynamic)b;
}
static void Main()
{
// Step 2: Get the MethodInfo object for the generic method
MethodInfo metSum = typeof(Program).GetMethod("Sum");
// Step 3: Construct the method generic with desired type of arguments
MethodInfo genMetSum = metSum.MakeGenericMethod(typeof(int));
// Step 4: Call the generic method with the specified type arguments
int result = (int)genMetSum.Invoke(null, new object[] { 1, 2 });
Console.WriteLine(result); // Output: 3
}
}

Code explanation

In the playground above:

  • Lines 7–10: We define a generic method Sum that receives two parameters as a and b and return their sum.

  • Line 15: We get the MethodInfo object for the generic method Sum with GetMethod().

  • Line 18: We construct a method generic named genMetSum with the int type of argument.

  • Line 21: We call the Invoke() method of genMetSum with arguments values of 1 and 2. We store the returned value in an integer variable, result.

  • Line 23: We print the output (stored in the result variable) to the console.

Copyright ©2024 Educative, Inc. All rights reserved