Reflection: The X-Ray Machine

Reflection: The X-Ray Machine in C#: Airport security cannot open every case, so they X-ray them.

The Analogy: Seeing Inside the Sealed Parcel

Airport security cannot open every case, so they X-ray them. The machine reports what is inside a sealed container without the owner's cooperation and without knowing anything about that particular case in advance — it works on luggage that was packed after the scanner was built.

Reflection is that machine pointed at code. Normally your program only touches things the compiler knew about: you wrote order.Customer, and the compiler resolved it. Reflection asks a different question — what does this type contain? — at run time, of a type you may never have compiled against. It can list properties, read and write them by name, invoke methods, construct instances, and reach into private fields.

The analogy carries the costs too. Scanning takes real time, so nobody X-rays every bag twice. The scanner sees the wiring inside a device, but reaching in and rearranging it is a different and far riskier act. And the moment you depend on what the scan reveals, you have coupled yourself to someone's internals rather than their contract — which is why reflection is the right tool for frameworks and the wrong tool for the ordinary code inside them.


Syntax or Core Structure

Type is the entry point. Everything else hangs off it: PropertyInfo, MethodInfo, FieldInfo, ConstructorInfo.

using System;
using System.Reflection;

class Order
{
    public int Id { get; set; }
    public string Customer { get; set; } = "";
    private decimal discount = 0.1m;

    public decimal Apply(decimal amount) => amount * (1 - discount);
    public override string ToString() => "Order " + Id + " for " + Customer;
}

class Program
{
    static void Main()
    {
        // A Type is the X-ray, not the parcel.
        Type type = typeof(Order);
        Console.WriteLine(type.Name + " has " + type.GetProperties().Length + " public properties");

        // Construct without naming the constructor.
        object order = Activator.CreateInstance(type)!;

        // Write properties by name.
        type.GetProperty("Id")!.SetValue(order, 7);
        type.GetProperty("Customer")!.SetValue(order, "Ada");
        Console.WriteLine(order);

        // Call a method by name; arguments are boxed into an object array.
        MethodInfo apply = type.GetMethod("Apply")!;
        Console.WriteLine("net: " + apply.Invoke(order, new object[] { 200m }));

        // Private state is visible with the right flags. Visible, not protected.
        FieldInfo discount = type.GetField("discount",
            BindingFlags.NonPublic | BindingFlags.Instance)!;

        Console.WriteLine("discount was " + discount.GetValue(order));
        discount.SetValue(order, 0.5m);
        Console.WriteLine("net now: " + apply.Invoke(order, new object[] { 200m }));
    }
}

Output:

Order has 2 public properties
Order 7 for Ada
net: 180.0
discount was 0.1
net now: 100.0

Nothing in Main after typeof(Order) mentions a member of Order in a way the compiler checks. "Customer" is a string; misspell it and GetProperty returns null, the ! turns that into a NullReferenceException, and you find out at run time. That trade — compile-time safety exchanged for run-time flexibility — is the entire character of reflection.

The last two lines are the uncomfortable part. private is a compiler rule, not a lock: with BindingFlags.NonPublic any code in the process can read and rewrite a private field. Access modifiers express design intent and prevent accidents; they are not a security boundary.


Technical Depth: The Machine's Running Costs

BindingFlags, and the default that surprises

GetMethod("Apply") finds public instance and static members only. Ask for anything else and you must say so:

FlagIncludes
Public / NonPublicVisibility — you need at least one
Instance / StaticKind — you need at least one
DeclaredOnlyThis type only, skipping inherited members
FlattenHierarchyStatic members from base classes too
IgnoreCaseCase-insensitive name matching

Supplying BindingFlags replaces the defaults rather than adding to them, so BindingFlags.NonPublic alone finds nothing at all: without Instance or Static there is no kind to search. That single rule accounts for most "my member is definitely there" confusion.

What it costs

Approximate cost of one call, relative to a direct one:

ApproachRelative costNotes
Direct call1xThe compiler resolved everything
Cached delegate from MethodInfo~1-2xCreateDelegate once, then normal invocation
Compiled expression tree~1-2xBuild once, reuse forever
MethodInfo.Invoke (cached info)~100xBoxing, argument array, security checks
GetMethod then Invoke each time~1000xMetadata search on every call

The shape of every fast reflection-based framework follows from that table: reflect once, at startup, and turn the result into something callable.

// Slow path, repeated.
type.GetMethod("Apply")!.Invoke(order, new object[] { 200m });

// Reflect once, then call a delegate at full speed.
var apply = (Func<Order, decimal, decimal>)Delegate.CreateDelegate(
    typeof(Func<Order, decimal, decimal>), type.GetMethod("Apply")!);

decimal net = apply(order, 200m);

Activator.CreateInstance(type) has the same problem and the same fix: build Expression.Lambda<Func<object>>(Expression.New(ctor)).Compile() once and call it a million times.

Exceptions arrive wrapped

A method invoked reflectively that throws does not throw that exception at the call site. MethodInfo.Invoke wraps it in TargetInvocationException, and the real one is ex.InnerException. Catch and unwrap, or every log entry says TargetInvocationException and tells you nothing.

Closing generic types at run time

An open generic type has holes; reflection can fill them:

Type listOfOrders = typeof(List<>).MakeGenericType(typeof(Order));
object list = Activator.CreateInstance(listOfOrders)!;

MethodInfo generic = typeof(JsonSerializer).GetMethod("Deserialize", ...)!;
MethodInfo closed = generic.MakeGenericMethod(targetType);

This is how a serializer deserializes into a type chosen from a configuration file, and how a DI container resolves IRepository<Order> from a registration of IRepository<>.

Scanning assemblies

The plugin pattern is three calls: load an assembly, list its types, keep the ones that fit.

IEnumerable<Type> plugins = Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface);

Note the direction: baseType.IsAssignableFrom(candidate), which reads backwards from how most people first write it. GetTypes() can throw ReflectionTypeLoadException when a dependency is missing, and its Types property still contains the ones that loaded — worth catching if you scan third-party assemblies.

Trimming, AOT, and the compile-time alternatives

Reflection defeats static analysis. A trimmer cannot see that GetProperty("Customer") needs Customer, so it removes it, and the app fails only when that path runs. .NET marks the risk explicitly with [RequiresUnreferencedCode] and lets you preserve members with [DynamicallyAccessedMembers], but the real answer for new code is to move the work to compile time:

Instead ofPreferWhy
GetProperty("Name") for a namenameof(Name)Checked by the compiler, free at run time
Reflection-based mappingA source generatorNo startup cost, trimming-safe
Invoke in a hot loopCached delegate or expressionTwo orders of magnitude faster
Reflecting to reach behaviourAn interfaceThe type system was built for this
dynamic for late bindingAn interface, or reflection with cachedynamic hides the same costs

Reflection is still the right tool for genuinely open-ended problems: a test runner that must find [Fact] methods in an assembly nobody compiled against, a serializer facing a type from a plugin, a container wiring up constructors it has never seen. If you can name the type at compile time, name it.


Real World Example: A Command Dispatcher

A console tool wants greet world and add 2 40 to reach the right method with converted arguments — without a giant switch that someone has to remember to update.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

[AttributeUsage(AttributeTargets.Method)]
sealed class CommandAttribute : Attribute
{
    public CommandAttribute(string name) => Name = name;
    public string Name { get; }
}

class Commands
{
    [Command("greet")]
    public void Greet(string who) => Console.WriteLine("hello " + who);

    [Command("add")]
    public void Add(int a, int b) => Console.WriteLine("sum " + (a + b));

    [Command("fail")]
    public void Fail() => throw new InvalidOperationException("nope");

    public void NotACommand() => Console.WriteLine("never reached");
}

class Dispatcher
{
    private readonly object target;
    private readonly Dictionary<string, MethodInfo> table =
        new(StringComparer.OrdinalIgnoreCase);

    public Dispatcher(object target)
    {
        this.target = target;
        foreach (MethodInfo m in target.GetType().GetMethods())
        {
            CommandAttribute? attr = m.GetCustomAttribute<CommandAttribute>();
            if (attr is not null) table[attr.Name] = m;
        }
    }

    public IEnumerable<string> Names => table.Keys.OrderBy(n => n);

    public void Run(string name, string[] args)
    {
        if (!table.TryGetValue(name, out MethodInfo? method))
        {
            Console.WriteLine("unknown command: " + name);
            return;
        }

        ParameterInfo[] parameters = method.GetParameters();
        if (parameters.Length != args.Length)
        {
            Console.WriteLine(name + " needs " + parameters.Length + " argument(s)");
            return;
        }

        object?[] converted = new object?[args.Length];
        for (int i = 0; i < args.Length; i++)
            converted[i] = Convert.ChangeType(args[i], parameters[i].ParameterType);

        try
        {
            method.Invoke(target, converted);
        }
        catch (TargetInvocationException ex)
        {
            Exception real = ex.InnerException!;
            Console.WriteLine("failed: " + real.GetType().Name + " " + real.Message);
        }
    }
}

class Program
{
    static void Main()
    {
        Dispatcher dispatcher = new Dispatcher(new Commands());
        Console.WriteLine("commands: " + string.Join(", ", dispatcher.Names));

        dispatcher.Run("greet", new[] { "world" });
        dispatcher.Run("add", new[] { "2", "40" });
        dispatcher.Run("add", new[] { "2" });
        dispatcher.Run("fail", Array.Empty<string>());
        dispatcher.Run("delete", Array.Empty<string>());
    }
}

Output:

commands: add, fail, greet
hello world
sum 42
add needs 2 argument(s)
failed: InvalidOperationException nope
unknown command: delete

Notice what reflection bought and what it cost. It bought the fact that Commands knows nothing about Dispatcher: adding a [Command("delete")] method is a one-line change, with no registration list to update and nothing to forget. It also bought argument conversion for free — ParameterInfo.ParameterType told the dispatcher that Add wants two int values, so Convert.ChangeType could turn "2" and "40" into numbers without any per-command code.

What it cost is compile-time safety. NotACommand is invisible to the dispatcher because it has no attribute, which is intentional — but if someone typed [Command("gret")], the compiler would happily accept it and the mistake would only surface as unknown command: greet at run time. That is the reflection bargain in miniature, and it is why the scan happens once in the constructor: the expensive, fragile part is paid at startup, and every subsequent Run is a dictionary lookup plus one Invoke.

The TargetInvocationException unwrap is the detail most people miss on their first dispatcher. Fail throws InvalidOperationException, but Invoke catches it, wraps it, and rethrows — so a catch (InvalidOperationException) around Invoke would never fire. Reaching ex.InnerException is what makes the error message say InvalidOperationException nope instead of something about a method invocation failing.


Common Mistakes

  1. Forgetting BindingFlags.Instance. GetField("x", BindingFlags.NonPublic) returns null because you replaced the default flags and never said whether you wanted a static or an instance member. Non-public members need NonPublic | Instance (or | Static).
  2. Assuming GetMethods or GetProperties returns a stable order. The order is unspecified and can change between runtimes. Sort by Name whenever the order is visible in output or drives behaviour.
  3. Catching the wrong exception around Invoke. The real exception is wrapped in TargetInvocationException; read InnerException.
  4. Calling GetMethod inside a loop. The lookup, not the invocation, is usually the expensive part. Resolve once, cache the MethodInfo, or build a delegate.
  5. Reversing IsAssignableFrom. It reads baseType.IsAssignableFrom(derivedType). Getting it backwards silently returns an empty plugin list.
  6. Treating private as security. Reflection reads private state, so never rely on access modifiers to protect a secret. They express design intent, not protection.
  7. Hard-coding member names as strings. GetProperty("Customer") survives a rename; nameof(Order.Customer) does not compile after one. Use nameof wherever the member is known at compile time.
  8. Shipping reflection into a trimmed or Native-AOT build without annotations. The trimmer removes members nothing appears to use, and the failure only appears at run time. Annotate with [DynamicallyAccessedMembers] or move to a source generator.

Best Practices

  • Do the discovery once — at startup or in a static constructor — and cache the results in a dictionary keyed by name.
  • Cache MethodInfo and PropertyInfo objects, and convert to Delegate.CreateDelegate or a compiled expression when the call is on a hot path.
  • Prefer GetCustomAttribute<T>() over filtering GetCustomAttributes() by type; it is shorter and states the intent.
  • Use nameof for every member name you already know, and reserve string lookups for names that genuinely arrive at run time.
  • Always unwrap TargetInvocationException before logging or rethrowing, so callers see the real failure.
  • Sort reflected member lists explicitly when the order matters, including in tests and console output.
  • Wrap Assembly.GetTypes() in a try/catch for ReflectionTypeLoadException and use its Types array when scanning assemblies you do not control.
  • Before reaching for reflection, ask whether an interface, a generic constraint, or a source generator solves the same problem at compile time.

Practice Exercises

  1. Write a Describe(object value) method that prints every public readable property as Name = Value, sorted by name, and prints (none) when the type has no such properties. Test it with a record and with an int.
  2. Extend the dispatcher so a [Command] method may return a value. Print the returned value when it is not void, and keep the existing behaviour for void methods.
  3. Build a tiny validator: define [Required] and [MaxLength(int)] attributes, then write IEnumerable<string> Validate(object model) that reflects over string properties and returns one message per violated rule.
  4. Measure the cost. Call a method one million times three ways — directly, through a cached MethodInfo.Invoke, and through a Delegate.CreateDelegate delegate — and print the three elapsed times with Stopwatch. Explain the ordering you see.