CodeBlanks Logo Icon CodeBlanks

MethodInfo.Invoke

C# course · Advanced · Lesson 46/83

Learn to invoke methods dynamically with MethodInfo.Invoke.

MethodInfo.Invoke

MethodInfo.Invoke(obj, args) calls a method via reflection. obj is the target instance (use null for static methods); args is the argument list as object[].

The return value comes back as object?; cast it to the real type. When the method name is known only at runtime (e.g. command handlers, plugin systems), the GetMethod + Invoke combination is used.

Static methods

To call static methods, pass null as the target to Invoke: mi.Invoke(null, args). For instance methods, the real instance must be provided; otherwise a TargetException is thrown.

This distinction comes from static members living at class level while instance members operate on a specific instance. Plugin systems typically call static entry points, while DI containers use instance methods.

Exercise Call a method with Invoke

In the Calculator class below, get the method with MethodInfo mi = typeof(Calculator).GetMethod("Square");. Call it with object result = mi.Invoke(calc, new object[] { 5 });. Print result with Console.WriteLine.

Show example solution
Get the method with MethodInfo mi = typeof(Calculator).GetMethod("Square");. Call it with object result = mi.Invoke(calc, new object[] { 5 });. Print with Console.WriteLine(result);.
Example solution:
using System;
using System.Reflection;

class Calculator
{
    public int Square(int x) => x * x;
}

class Program
{
    static void Main()
    {
        Calculator calc = new Calculator();
        MethodInfo mi = typeof(Calculator).GetMethod("Square");
        object result = mi.Invoke(calc, new object[] { 5 });
        Console.WriteLine(result);
    }
}

Test yourself

  1. What is the first parameter of Invoke?

    • The method name
    • The parameter types
    • The target instance (null for static)
    • The return type
    Show answer

    The target instance (null for static) — Correct. The first parameter is the target instance; null for static methods.

  2. Complete the Invoke call

    object result = mi.____(obj, new object[] { 5 });
    Show answer
    object result = mi.Invoke(obj, new object[] { 5 });
  3. Match the parameter to its meaning

    obj
    Target instance
    null
    For static
    new object[] {}
    Empty args
    new object[] { 5 }
    Single argument

All lessons in Advanced