skip to content

A C# CLI tool dispatches commands with MethodInfo.Invoke and its catch (CommandFailedException) never fires; why, and how does MethodInfo.CreateDelegate change that and the per-call cost?

level: seniorimportance: should knowfreq 30%

answer

  1. the exception arrives in a wrapper
  2. object array in, object out
  3. boxing on every call
  4. bind once, call typed
  5. DoNotWrapExceptions

basics

~10 s

MethodInfo.Invoke wraps whatever the target throws in TargetInvocationException, and boxes arguments and results on every call. A delegate from CreateDelegate<TDelegate>(), created once and cached, makes a typed call that throws unwrapped and allocates nothing.

solid answer

~30 s

`Invoke` reports any exception the target throws as `TargetInvocationException`, with the original in `InnerException`, so `catch (CommandFailedException)` is skipped; argument-count and argument-type errors are thrown directly, before the call. You can unwrap `InnerException`, pass `BindingFlags.DoNotWrapExceptions`, or avoid `Invoke`. Each `Invoke` also takes an `object?[]`, checks the arguments against the parameters and boxes value-type results. `run.CreateDelegate<Func<DeployCommand, string, int>>()` binds once; calling the cached delegate is an ordinary typed call that throws `CommandFailedException` directly and does no boxing. Build it once per method, never per call.

code

csharp · 31 lines
csharp
#:property PublishAot=false
using System.Reflection;

var cmd = new DeployCommand();
MethodInfo run = typeof(DeployCommand).GetMethod(nameof(DeployCommand.Run))!;

try { run.Invoke(cmd, ["prod"]); }
catch (CommandFailedException) { Console.WriteLine("caught directly"); }
catch (TargetInvocationException e) { Console.WriteLine($"wrapped: {e.InnerException!.GetType().Name}"); }

try { run.Invoke(cmd, BindingFlags.DoNotWrapExceptions, null, ["prod"], null); }
catch (CommandFailedException) { Console.WriteLine("unwrapped with DoNotWrapExceptions"); }

var call = run.CreateDelegate<Func<DeployCommand, string, int>>();   // once, then cache
try { call(cmd, "prod"); }
catch (CommandFailedException) { Console.WriteLine("delegate: caught directly"); }

object?[] argv = ["dev"];
for (int i = 0; i < 1000; i++) { run.Invoke(cmd, argv); call(cmd, "dev"); }   // warm up
long a0 = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 100_000; i++) run.Invoke(cmd, argv);
long a1 = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 100_000; i++) call(cmd, "dev");
long a2 = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"Invoke: {a1 - a0} bytes, delegate: {a2 - a1} bytes");

class CommandFailedException(string message) : Exception(message);
class DeployCommand
{
    public int Run(string env) => env == "prod" ? throw new CommandFailedException("no approval") : env.Length;
}

go deeper

for a junior

Know that MethodInfo.Invoke calls a method found by reflection and that exceptions from that method come back inside TargetInvocationException.

for a middle

Explain the object?[] arguments, boxing of value types and which failures are or are not wrapped, and show the DoNotWrapExceptions overload.

for a senior

Diagnose the missed catch, replace per-call Invoke with cached CreateDelegate delegates, and back any speed claim with an allocation measurement or a benchmark, not one stopwatch run.

for a principal

Decide where reflection may sit in a codebase: startup-only discovery with typed delegates afterwards keeps the hot path free of reflection costs and wrapped exceptions.

## What `MethodInfo.Invoke` does on every call `MethodInfo.Invoke(object? obj, object?[]? parameters)` calls a method you found by reflection. Its signature is the whole story: the target is `object`, the arguments travel in an `object?[]`, and the result comes back as `object?`. Because the call is not compiled against the method's real signature, the runtime does work on every call that a direct call never needs. - It checks that the target is an instance of the declaring type and that the argument count and argument types fit the parameters. - Value-type arguments and return values are **boxed**: an `int` return becomes a heap-allocated object. - In the .NET 10 runtime source, the first call takes a slow path, and a later call emits a small IL stub for the method when the runtime supports dynamic code (`RuntimeFeature.IsDynamicCodeSupported`), so repeated calls get cheaper, but they still go through the steps above. - Exceptions thrown by the target are **wrapped**. ## Why `catch (CommandFailedException)` never fires Any exception the invoked method throws arrives as a **`TargetInvocationException`**, with the original exception in `InnerException`. A CLI tool that dispatches commands through `Invoke` and writes `catch (CommandFailedException)` around it never enters that block; the user sees a generic "Exception has been thrown by the target of an invocation" unless the handler unwraps it. The .NET 7 breaking-change notes made this consistent: since .NET 7, everything the target throws after argument validation is wrapped. Problems found *before* the call are not wrapped; they are reported directly: | Problem | Exception | Wrapped? | |---|---|---| | Target method throws | `TargetInvocationException` (original in `InnerException`) | yes | | Wrong number of arguments | `TargetParameterCountException` | no | | Argument of the wrong type | `ArgumentException` | no | | Target object of the wrong type | `TargetException` | no | There are three ways out: 1. Catch `TargetInvocationException` and handle its `InnerException`. When you rethrow it, keep the original stack trace (rethrowing exceptions is covered with exception handling). 2. Call the overload `Invoke(obj, BindingFlags.DoNotWrapExceptions, binder: null, parameters, culture: null)`. With that flag, the target's exception propagates as if the call were direct. 3. Stop using `Invoke` for the hot path and call through a delegate, which never wraps. ## `MethodInfo.CreateDelegate<TDelegate>()`: pay once, call typed `CreateDelegate<TDelegate>()` binds a `MethodInfo` to a delegate type whose signature matches the method. For an instance method you choose between two forms: - **Open instance:** the delegate's first parameter is the target. `run.CreateDelegate<Func<DeployCommand, string, int>>()` gives a delegate you call as `call(cmd, "prod")`, which suits a registry that serves many command objects. - **Closed over a target:** `run.CreateDelegate<Func<string, int>>(cmd)` fixes the instance and leaves the method's own parameters. A signature that does not match the method throws `ArgumentException` when you create the delegate, not when you call it. Once created, the delegate is an ordinary typed call: arguments are not packed into an array, an `int` return is not boxed, and a thrown `CommandFailedException` reaches your `catch` unwrapped. Create it **once per method** (at startup, or lazily into a `Dictionary<string, Func<...>>`) and reuse it. Calling `CreateDelegate` inside the loop would bring back a per-call setup cost. ## Measuring the difference honestly A single `Stopwatch` run says little about a call that takes nanoseconds. Allocation is easier to pin down: the snippet reads `GC.GetAllocatedBytesForCurrentThread()` around 100,000 calls of each kind after a warm-up. On this machine with the .NET 10 runtime, `Invoke` allocated 2,400,000 bytes (24 bytes a call, the boxed `int` result, since the argument array was reused) and the delegate allocated 0. The exact number depends on the runtime, the platform and the method's signature, but the mechanism does not: `Invoke` boxes value types and the delegate does not. For time, use a benchmarking harness rather than a loop with a stopwatch. ## Choosing the call mechanism - The method's signature is known at compile time: use a cached `CreateDelegate<TDelegate>()`. - The signature is not known, but you call it often: `MethodInvoker.Create(method)`, cached, offers `Invoke` overloads that take arguments without an array; it still works in `object`. - It runs once at startup: plain `Invoke` is fine. Know that it wraps exceptions. - The member is private and known by name: `[UnsafeAccessor]` is the .NET 8 alternative, covered separately.

  • Which `Invoke` failures are not wrapped in `TargetInvocationException`?
    Failures found while validating the call before the target runs: a wrong argument count throws `TargetParameterCountException`, an argument of the wrong type throws `ArgumentException`, and a target object of the wrong type throws `TargetException`. Only exceptions raised by the invoked method itself are wrapped, unless you pass `BindingFlags.DoNotWrapExceptions`.
  • When would you use `MethodInvoker` instead of `CreateDelegate`?
    When the method's signature is not known at compile time, so no delegate type can be written for it, but the call is still frequent. `MethodInvoker.Create(method)`, cached, offers `Invoke` overloads that take up to four arguments without an `object?[]`. It still works in `object`, so value types are boxed. A delegate stays the cheaper option whenever you can name the signature.
  • What happens if you call `CreateDelegate<Func<string, string>>(cmd)` on `int Run(string env)`?
    It throws `ArgumentException` immediately, because the delegate's return type does not match the method's. That is the useful property of `CreateDelegate`: a signature mismatch fails once, when the delegate is built at startup, instead of on each call as it would with `Invoke`.

  • MethodInfo.Invoke rethrows the target's exception unchanged
  • Argument count errors from Invoke also arrive wrapped in TargetInvocationException
  • Calling CreateDelegate on every invocation is as fast as caching it
  • Invoke is slow because it repeats the GetMethod lookup each call
  • A cached delegate still boxes value-type return values