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:
-
Define a generic method.
-
Get the
MethodInfoobject for the generic method. -
Construct the method generic with the desired type of arguments.
-
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 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}}
Code explanation
In the playground above:
-
Lines 7–10: We define a generic method
Sumthat receives two parameters asaandband return their sum. -
Line 15: We get the
MethodInfoobject for the generic methodSumwithGetMethod(). -
Line 18: We construct a method generic named
genMetSumwith theinttype of argument. -
Line 21: We call the
Invoke()method ofgenMetSumwith arguments values of1and2. We store the returned value in an integer variable,result. -
Line 23: We print the output (stored in the
resultvariable) to the console.
Free Resources