Reflection in C# allows you to inspect and interact with types dynamically at runtime. It is useful for scenarios like plugin systems, dependency injection, and working with unknown assemblies.
Getting Started with Reflection
To use reflection, include the System.Reflection
namespace:
using System;
using System.Reflection;
Invoking a Method Dynamically
You can use reflection to call methods on an object when you don't know the method name at compile time.
class Sample
{
public void SayHello() => Console.WriteLine("Hello from Reflection!");
}
var sample = new Sample();
MethodInfo method = typeof(Sample).GetMethod("SayHello");
method?.Invoke(sample, null);
// Output: Hello from Reflection!
Invoking Methods with Parameters
If a method requires parameters, pass them as an object array:
class MathOperations
{
public int Add(int a, int b) => a + b;
}
var math = new MathOperations();
MethodInfo method = typeof(MathOperations).GetMethod("Add");
object result = method?.Invoke(math, new object[] { 5, 3 });
Console.WriteLine(result); // Output: 8
Working with Static Methods
For static methods, pass null
as the target object:
class Utility
{
public static string GetMessage() => "Static method called!";
}
MethodInfo method = typeof(Utility).GetMethod("GetMessage");
object result = method?.Invoke(null, null);
Console.WriteLine(result); // Output: Static method called!
- Reflection is slower than direct method calls because it bypasses compile-time optimizations.
- Use
Delegate.CreateDelegate
to improve performance when invoking frequently:
Func<int, int, int> add = (Func<int, int, int>)Delegate.CreateDelegate(
typeof(Func<int, int, int>),
typeof(MathOperations).GetMethod("Add")
);
Console.WriteLine(add(5, 3)); // Output: 8
Conclusion
Reflection in C# is a powerful tool for dynamic method invocation. While it introduces some performance overhead, it is invaluable in scenarios requiring runtime flexibility, such as plugins, serialization, and dynamic dependency loading.