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)orobject.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:
GetMethodreturnsnullif the method name is wrong, causing aNullReferenceExceptiononInvoke. - Wrong parameters: Passing incorrect number or types of parameters causes
TargetParameterCountExceptionorArgumentException. - Static vs instance: For static methods, pass
nullas the target object; for instance methods, pass the object instance. - Access modifiers:
GetMethodonly finds public methods by default; useBindingFlagsto 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.GetMethodto find the method by name. - Pass the correct target object:
nullfor static, instance for non-static. - Provide parameters as an object array matching the method signature.
- Check for
nullMethodInfo to avoid exceptions. - Use
BindingFlagsto 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.