[C#] How to Dynamically Call Methods by String Name Using Reflection

Usually, method calls are written as instance.MethodName(). However, in scenarios such as plugin systems or dynamic script execution, the name of the method to be called might not be known until runtime.

In such cases, you can execute methods by specifying their names as strings using a combination of Type.GetMethod and MethodInfo.Invoke.

目次

Implementing Dynamic Execution with the Invoke Method

The following sample code implements a process to call calculation methods defined in a Calculator class by specifying strings (like “Add” or “Multiply”). Arguments are also passed dynamically as object arrays.

Sample Code

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        // 1. Create an instance of the class containing the methods
        var calc = new Calculator();

        // 2. Get type information of the class
        Type targetType = calc.GetType();

        Console.WriteLine("--- Dynamic Method Invocation ---");

        // Example 1: Call Add method
        // Pass 10 and 20 as arguments
        CallDynamicMethod(targetType, calc, "Add", new object[] { 10, 20 });

        // Example 2: Call Subtract method
        // Pass 50 and 15 as arguments
        CallDynamicMethod(targetType, calc, "Subtract", new object[] { 50, 15 });

        // Example 3: Call Multiply method
        CallDynamicMethod(targetType, calc, "Multiply", new object[] { 5, 5 });

        // Check behavior when specifying a non-existent method
        CallDynamicMethod(targetType, calc, "Divide", new object[] { 100, 2 });
    }

    /// <summary>
    /// Executes a named method using Reflection
    /// </summary>
    /// <param name="type">Type information</param>
    /// <param name="instance">Target instance</param>
    /// <param name="methodName">Method name</param>
    /// <param name="args">Argument array</param>
    public static void CallDynamicMethod(Type type, object instance, string methodName, object[] args)
    {
        // 1. Get method info (searches for public instance methods)
        MethodInfo methodInfo = type.GetMethod(methodName);

        if (methodInfo == null)
        {
            Console.WriteLine($"[Error] Method '{methodName}' was not found.");
            return;
        }

        try
        {
            // 2. Execute method (Invoke)
            // 1st Arg: Instance, 2nd Arg: Array of arguments
            object result = methodInfo.Invoke(instance, args);

            Console.WriteLine($"Executed: {methodName}({string.Join(", ", args)}) => Result: {result}");
        }
        catch (ArgumentException)
        {
            Console.WriteLine($"[Error] Arguments for '{methodName}' do not match.");
        }
    }
}

// Class providing calculation functions
public class Calculator
{
    public int Add(int a, int b) => a + b;
    
    public int Subtract(int a, int b) => a - b;
    
    public int Multiply(int a, int b) => a * b;
    
    // Divide method is intentionally not defined
}

Explanation and Technical Points

1. Type.GetMethod Method

This retrieves information about a public method with the specified name as a MethodInfo object. If method overloads (methods with the same name but different arguments) exist, this method alone cannot identify the correct one. In that case, you must use another overload, GetMethod(string name, Type[] types), to specify the argument types explicitly.

2. MethodInfo.Invoke Method

This executes the actual processing based on the retrieved method information.

  • First Argument (obj): The target instance to execute the method on. Specify null for static methods.
  • Second Argument (parameters): An object array containing the arguments to pass to the method. Pass null if the method has no arguments.

3. Handling Return Values

The return value of the Invoke method is of type object. If the called method’s return type is void, it returns null. To use the value, you need to cast it to the appropriate type (e.g., (int)result).

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次