"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Dynamically Invoke Generic Methods with Runtime-Determined Type Arguments in C#?

How Can I Dynamically Invoke Generic Methods with Runtime-Determined Type Arguments in C#?

Posted on 2025-03-22
Browse:892

How Can I Dynamically Invoke Generic Methods with Runtime-Determined Type Arguments in C#?

Calling Generic Methods with Dynamic Type Arguments

Problem

In your scenario, you want to iterate through a collection of interfaces in a specific namespace and dynamically invoke a generic method for each interface. However, you encounter compile-time errors due to the unknown type arguments at compile time.

Solution

To dynamically call generic methods with runtime-known type arguments, you can use reflection as follows:

  1. Get the generic method information: Use the Type.GetMethod method to retrieve the generic method definition.
  2. Generate the generic method instance: Call the MakeGenericMethod method on the generic method definition to generate the specific method instance for the desired type argument.
  3. Invoke the generic method instance: Use the Invoke method to invoke the generated generic method instance with the required arguments.

Example Code

using System;
using System.Linq;
using System.Reflection;

public class TestClass
{
    public static void CallGeneric()
    {
        Console.WriteLine($"Generic type: {typeof(T)}");
    }

    public static void Main()
    {
        var assembly = Assembly.GetExecutingAssembly();

        var interfaces = assembly.GetTypes()
            .Where(t => t.Namespace == "MyNamespace.Interfaces");

        var genericMethod = typeof(TestClass).GetMethod("CallGeneric");

        foreach (var interfaceType in interfaces)
        {
            var genericMethodInstance = genericMethod.MakeGenericMethod(interfaceType);
            genericMethodInstance.Invoke(null, null); // No target or arguments needed
        }
    }
}

In this example:

  • The CallGeneric method is defined as a generic method that prints the generic type argument.
  • We fetch all types from a specific namespace that inherit from MyNamespace.Interfaces.
  • We use reflection to obtain the generic method CallGeneric and create a generic method instance for each interface type.
  • We invoke the generic method instance without any target or arguments since it's a static method without any parameters.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3