0
0
CsharpHow-ToBeginner · 3 min read

How to Invoke Method Using Reflection in C# - Simple Guide

In C#, you can invoke a method using reflection by first getting the Type of the class, then retrieving the MethodInfo object with GetMethod, and finally calling Invoke on that method with the target object and parameters. This allows you to run methods dynamically at runtime without direct calls.
📐

Syntax

To invoke a method using reflection, follow these steps:

  • Get the Type: Use typeof(ClassName) or object.GetType().
  • Get MethodInfo: Call GetMethod("MethodName") on the Type.
  • Invoke Method: Use MethodInfo.Invoke(targetObject, parametersArray).

The targetObject is the instance to call the method on (or null for static methods), and parametersArray is an object array of arguments.

csharp
Type type = typeof(MyClass);
MethodInfo method = type.GetMethod("MyMethod");
object result = method.Invoke(myObjectInstance, new object[] { arg1, arg2 });
💻

Example

This example shows how to invoke a method named Greet that takes a string parameter and returns a greeting message.

csharp
using System;
using System.Reflection;

public class Person
{
    public string Greet(string name)
    {
        return $"Hello, {name}!";
    }
}

class Program
{
    static void Main()
    {
        Person person = new Person();
        Type type = typeof(Person);
        MethodInfo greetMethod = type.GetMethod("Greet");

        object result = greetMethod.Invoke(person, new object[] { "Alice" });
        Console.WriteLine(result);
    }
}
Output
Hello, Alice!
⚠️

Common Pitfalls

  • Method name typo: GetMethod returns null if the method name is wrong, causing a NullReferenceException on Invoke.
  • Wrong parameters: Passing incorrect number or types of parameters causes TargetParameterCountException or ArgumentException.
  • Static vs instance: For static methods, pass null as the target object; for instance methods, pass the object instance.
  • Access modifiers: GetMethod only finds public methods by default; use BindingFlags to access non-public methods.
csharp
/* Wrong method name example */
Type type = typeof(Person);
MethodInfo method = type.GetMethod("WrongName");
// method is null, calling method.Invoke(...) will throw

/* Correct way with check */
if (method != null)
{
    method.Invoke(person, new object[] { "Alice" });
}
else
{
    Console.WriteLine("Method not found.");
}
📊

Quick Reference

Remember these key points when invoking methods with reflection:

  • Use Type.GetMethod to find the method by name.
  • Pass the correct target object: null for static, instance for non-static.
  • Provide parameters as an object array matching the method signature.
  • Check for null MethodInfo to avoid exceptions.
  • Use BindingFlags to access private or static methods if needed.

Key Takeaways

Use Type.GetMethod and MethodInfo.Invoke to call methods dynamically in C#.
Always check if MethodInfo is null before invoking to avoid errors.
Pass the correct target object and parameters matching the method signature.
Use BindingFlags to access non-public or static methods.
Reflection allows flexible method calls but can be slower than direct calls.