reflection
TargetException
event handler
error handling
C# programming

TargetException thrown while using reflection to add an event handler

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

TargetException during reflective event subscription usually means the runtime was given the wrong target object or an incompatible delegate binding. Reflection can attach an event handler successfully, but only if the event belongs to the instance you pass and the delegate exactly matches the event’s handler type. The fix is to inspect the event metadata and the target instance rather than treating the exception as mysterious reflection noise.

How Reflection-Based Event Wiring Works

A reflective subscription has five moving parts:

  • the type that declares the event
  • the EventInfo
  • the publisher instance, if the event is not static
  • the handler method
  • a delegate whose type matches the event signature exactly

Here is a working example:

csharp
1using System;
2using System.Reflection;
3
4public class Publisher
5{
6    public event EventHandler? Started;
7    public void Raise() => Started?.Invoke(this, EventArgs.Empty);
8}
9
10public class Subscriber
11{
12    public void OnStarted(object? sender, EventArgs e)
13    {
14        Console.WriteLine("Started event received");
15    }
16}
17
18public static class Program
19{
20    public static void Main()
21    {
22        var publisher = new Publisher();
23        var subscriber = new Subscriber();
24
25        EventInfo? eventInfo = typeof(Publisher).GetEvent("Started");
26        MethodInfo? method = typeof(Subscriber).GetMethod(nameof(Subscriber.OnStarted));
27
28        Delegate handler = Delegate.CreateDelegate(
29            eventInfo!.EventHandlerType!,
30            subscriber,
31            method!
32        );
33
34        eventInfo.AddEventHandler(publisher, handler);
35        publisher.Raise();
36    }
37}

This succeeds because the event belongs to publisher, while the method belongs to subscriber, and the delegate signature matches EventHandler.

The Most Common Cause of TargetException

The most common mistake is passing the wrong target to AddEventHandler. For an instance event, the first argument must be the object that owns the event.

If the event belongs to Publisher, this is correct:

csharp
eventInfo.AddEventHandler(publisher, handler);

This is not:

csharp
eventInfo.AddEventHandler(subscriber, handler);

That mistake is enough to trigger TargetException, because the runtime sees an event being attached to an instance that does not actually declare it.

Static Events Are Different

For static events, the target instance should be null.

csharp
EventInfo? eventInfo = typeof(SomeType).GetEvent("GlobalChanged");
eventInfo!.AddEventHandler(null, handler);

If you pass a concrete instance for a static event, or null for an instance event, reflection will reject the call.

Match the Delegate Signature Exactly

The handler method must match the event’s delegate type. Reflection does not “almost” bind the method for you.

csharp
1public class MyArgs : EventArgs
2{
3    public string Message { get; set; } = string.Empty;
4}
5
6public void OnChanged(object? sender, MyArgs e)
7{
8    Console.WriteLine(e.Message);
9}

If the event type is EventHandler<MyArgs>, a plain EventHandler method is not interchangeable. Check eventInfo.EventHandlerType before creating the delegate if you are in doubt.

Validate the Metadata Before Binding

You can fail fast with much clearer errors by validating the reflection results first.

csharp
1EventInfo? eventInfo = targetType.GetEvent("Started");
2if (eventInfo is null)
3{
4    throw new InvalidOperationException("Event not found.");
5}
6
7MethodInfo? method = subscriber.GetType().GetMethod("OnStarted");
8if (method is null)
9{
10    throw new InvalidOperationException("Handler method not found.");
11}

That is much easier to debug than catching a generic TargetException after several reflective steps have already failed.

Common Pitfalls

  • Passing the subscriber instance instead of the publisher instance into AddEventHandler.
  • Using null for an instance event or a concrete instance for a static event.
  • Creating a delegate whose method signature does not exactly match the event type.
  • Skipping validation of EventInfo, MethodInfo, and EventHandlerType before binding.
  • Treating reflection as magical when the runtime is actually enforcing very strict target and signature rules.

Summary

  • 'TargetException often means the wrong target object was passed to AddEventHandler.'
  • Use the publisher instance for instance events and null for static events.
  • The delegate must match the event’s handler type exactly.
  • Validate reflection metadata before attaching the handler.
  • Reflection works reliably here, but only when the event, target, and delegate line up precisely.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.