Dynamic Method Invocation in C# using `MethodInfo.Invoke()`: Mastering Reflection

Learn how to use C#'s `MethodInfo.Invoke()` method for dynamic method calls at runtime. This tutorial explains reflection, demonstrates using `MethodInfo.Invoke()` to call methods whose names are only known at runtime, and highlights its applications in flexible and adaptable C# applications.



Dynamic Method Invocation Using C#'s `MethodInfo.Invoke()`

C#'s `MethodInfo.Invoke()` method allows you to call a method on an object dynamically at runtime. This is a powerful feature of reflection, enabling flexible and adaptable code.

Understanding `MethodInfo.Invoke()`

The `MethodInfo.Invoke()` method is part of the .NET Framework's reflection capabilities. Reflection lets you examine and interact with types and their members (like methods) at runtime, rather than at compile time. `MethodInfo.Invoke()` lets you call a method whose name you know only at runtime.

`MethodInfo.Invoke()` Syntax


public object? Invoke(object? obj, object[] parameters);

It takes two parameters:

  • obj (object): The object instance on which to call the method. For static methods, pass `null`.
  • parameters (object[]): An array of objects representing the method's arguments.

It returns an `object` representing the method's return value (or `null` if the method's return type is `void`).

Example 1: Calling Instance and Static Methods


// ... (MyClass class with SayHello and Add methods) ...

public class Example {
    public static void Main(string[] args) {
        // ... (code to get MethodInfo objects and invoke methods dynamically) ...
    }
}

Example 2: Invoking Multiple Methods


// ... (Car class with StartEngine, Accelerate, Brake methods) ...

public class Example {
    public static void Main(string[] args) {
        // ... (code to get MethodInfo objects and invoke methods dynamically) ...
    }
}

Important Considerations

  • Exception Handling: `Invoke()` throws exceptions that the called method throws. Always wrap it in a `try-catch` block.
  • Performance: Reflection can be slower than directly calling a method. Use judiciously.
  • Readability: Overuse of reflection can make your code harder to understand and maintain.