Reflection in C#: Inspect Types and Invoke Methods at Runtime

Reflection lets code inspect types at run time: which methods, properties and attributes a class has, what parameters a method takes, and so on. It can also create objects and call members by name when the type is not known at compile time. Serializers, dependency injection containers, test frameworks and ORMs are built on it.

Everything starts from a System.Type object, which you get with typeof(SomeClass) for a known type or obj.GetType() for an object you have. The examples below use this class:

public class ReflectionExample
{
    public string Name { get; set; } = "Example";

    public void SampleMethod1(string message)
    {
        Console.WriteLine("My name is SampleMethod1");
        Console.WriteLine("Your message is " + message);
    }

    public void SampleMethod2(int id)
    {
        Console.WriteLine("My name is SampleMethod2");
        Console.WriteLine("Your id is " + id);
    }
}

List the methods of a type

using System.Reflection;

MethodInfo[] methods = typeof(ReflectionExample).GetMethods(
    BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

foreach (MethodInfo method in methods.Where(m => !m.IsSpecialName).OrderBy(m => m.Name))
{
    Console.WriteLine(method.Name);
}

Output:

SampleMethod1
SampleMethod2

Calling GetMethods() with no arguments returns more than you might expect: the public methods inherited from object (ToString, Equals, GetHashCode, GetType) and the hidden get_Name and set_Name methods that implement the property. The BindingFlags above restrict the result to public instance methods declared on the class itself, and IsSpecialName filters out the property accessors.

Two details trip people up. When you pass any BindingFlags, you must include both an accessibility flag (Public or NonPublic) and a scope flag (Instance or Static), or you get an empty array. And the order of the returned methods is not guaranteed, which is why the loop sorts them.

Read a method’s parameters

MethodInfo m = typeof(ReflectionExample).GetMethod(nameof(ReflectionExample.SampleMethod1))!;

foreach (ParameterInfo p in m.GetParameters())
{
    Console.WriteLine($"{p.Name}: {p.ParameterType.Name}");
}
// message: String

GetMethod returns null when no method has that name, and throws AmbiguousMatchException when there are several overloads. For overloaded methods, pass the parameter types: GetMethod("SampleMethod1", [typeof(string)]). Using nameof instead of a string literal means a rename in the IDE updates the call too.

Create an object and call a method by name

This is late binding: deciding at run time what to create and call.

Type type = typeof(ReflectionExample);
object instance = Activator.CreateInstance(type)!;

MethodInfo method = type.GetMethod("SampleMethod1")!;
method.Invoke(instance, ["Hello Method!"]);

Output:

My name is SampleMethod1
Your message is Hello Method!

Activator.CreateInstance calls the public parameterless constructor. In real code the Type usually comes from a string, for example Type.GetType("MyApp.Plugins.CsvExporter, MyApp.Plugins"), which needs the namespace-qualified name and, for types outside the current assembly, the assembly name.

If the invoked method throws, Invoke wraps the exception in a TargetInvocationException. The real error is in its InnerException, so log that one.

Read and write properties

var example = new ReflectionExample();
PropertyInfo nameProperty = typeof(ReflectionExample).GetProperty("Name")!;

Console.WriteLine(nameProperty.GetValue(example));   // Example
nameProperty.SetValue(example, "Changed");
Console.WriteLine(example.Name);                     // Changed

GetProperties() returns all of them, which is the basis of every “copy matching properties from one object to another” helper. Attributes on members are read the same way, with GetCustomAttribute<T>(); the enum description post below shows an example.

Performance

Reflection is much slower than a direct call. Looking up a member by name searches metadata, and Invoke has to box arguments into an object[] and check them. Two habits keep the cost down:

  • Look members up once and cache the MethodInfo or PropertyInfo, for example in a static field or dictionary, instead of calling GetMethod on every call.
  • If you call the same method many times, turn it into a delegate once. After that, calls cost the same as a normal delegate call:
var call = method.CreateDelegate<Action<string>>(instance);
call("Fast call");

The generic CreateDelegate<T> is available from .NET 5; on older versions use (Action<string>)method.CreateDelegate(typeof(Action<string>), instance).

Trimming and Native AOT

When you publish a trimmed app or compile with Native AOT, the trimmer removes members it cannot see being used. Members you only reach through reflection by name can disappear, and the compiler warns about such calls (IL2026, IL2075 and related). Annotating types with [DynamicallyAccessedMembers] tells the trimmer what to keep. Where you can, prefer source generators, as System.Text.Json and logging already do, so the work happens at compile time.

Related examples

Leave a Comment