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.
We can follow these steps to call a generic method using reflection:
Define a generic method.
Get the MethodInfo
object for the generic method.
Construct the method generic with the desired type of arguments.
Call the generic method with the specified type of arguments.
Let’s consider the following playground:
using System;using System.Reflection;class Program{// Step 1: Define a generic methodpublic 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 methodMethodInfo metSum = typeof(Program).GetMethod("Sum");// Step 3: Construct the method generic with desired type of argumentsMethodInfo genMetSum = metSum.MakeGenericMethod(typeof(int));// Step 4: Call the generic method with the specified type argumentsint result = (int)genMetSum.Invoke(null, new object[] { 1, 2 });Console.WriteLine(result); // Output: 3}}
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.