How to call a static method using reflection in C#

By Tan Lee Published on Mar 04, 2025  200
To call a static method using reflection in C#, follow these steps:
  • Get the Type of the class.
  • Retrieve the MethodInfo of the static method using GetMethod().
  • Invoke the method using MethodInfo.Invoke().

Reflection allows you to access properties and methods dynamically at runtime. Below is an example of invoking a static method using reflection:

MethodInfo methodInfo = typeof(Type).GetMethod(StaticMethodName, BindingFlags.Static | BindingFlags.Public);
var result = (ReturnType)methodInfo.Invoke(null, null);

Note: The above example calls a parameterless static method. If the method requires parameters, pass them as arguments like this:

methodInfo.Invoke(null, new object[] { param1, param2 });

For example:

using System;
using System.Reflection;

class Example
{
    public static void Greet(string name)
    {
        Console.WriteLine($"Hello, {name}!");
    }
}

class Program
{
    static void Main()
    {
        // Get the Type of the class
        Type type = typeof(Example);
        
        // Get MethodInfo for the static method
        MethodInfo methodInfo = type.GetMethod("Greet", BindingFlags.Static | BindingFlags.Public);
        
        // Invoke the static method with a parameter
        methodInfo.Invoke(null, new object[] { "Alice" });
    }
}

In this example:

  • typeof(Example): Gets the type of the class.
  • GetMethod("Greet", BindingFlags.Static | BindingFlags.Public): Retrieves the static method.
  • Invoke(null, new object[] { "Alice" }): Calls the method, passing "Alice" as an argument.