In C#, when a document window subscribes to a settings service's event, which of the two objects does the subscription keep alive, and why?
answer
- direction of the reference
- what += stores, and where
- Delegate.Target
- the publisher's invocation list
basics
~20 sThe publisher keeps the subscriber alive. The += operator stores a delegate in the settings service's event field, and that delegate's Target is the window or a closure that captured it, so the service reaches the window until it unsubscribes.
solid answer
~30 sThe reference runs from the publisher to the subscriber. `settings.Changed += OnSettingsChanged` creates a delegate that records the method in `Delegate.Method` and its receiver, the window, in `Delegate.Target`, and appends it to the invocation list held in the service's event field. As long as the service is reachable, so is the window, its controls and the document it loaded. The subscription adds nothing in the other direction, so a short-lived publisher with a long-lived subscriber is harmless. The dangerous shape is a long-lived publisher, such as an app-wide service or any `static` event, with short-lived subscribers that never call `-=`.
code
csharp · 20 linesvar settings = new SettingsService();
var window = new DocumentWindow(settings);
Delegate stored = settings.Subscribers()[0];
Console.WriteLine(ReferenceEquals(stored.Target, window)); // True: the service holds the window
Console.WriteLine(stored.Method.Name); // OnSettingsChanged
sealed class SettingsService
{
public event EventHandler? Changed;
public Delegate[] Subscribers() => Changed?.GetInvocationList() ?? [];
}
sealed class DocumentWindow
{
public DocumentWindow(SettingsService settings) =>
settings.Changed += OnSettingsChanged; // stores (this, OnSettingsChanged)
private void OnSettingsChanged(object? sender, EventArgs e) { }
}go deeper
Recall the direction: the publisher's event field holds a delegate, and the delegate's Target is the subscriber. Say that unsubscribing with -= is what breaks the chain.
Explain what a delegate records for an instance method versus a capturing lambda, and why a short-lived publisher with a long-lived subscriber is harmless.
Show you can predict a leak from lifetimes alone: app-wide services and static events with short-lived subscribers, and where the matching -= belongs.
Frame the lifetime mismatch as an architectural property: which components may expose long-lived events, and how ownership of each subscription is made explicit.
## What `+=` actually stores An **event** in C# is, for a field-like declaration such as `public event EventHandler? Changed;`, a private field of a delegate type plus an `add` and a `remove` accessor that outside code reaches through `+=` and `-=`. When a window writes ```csharp settings.Changed += OnSettingsChanged; ``` the compiler turns the method group `OnSettingsChanged` into a new `EventHandler` delegate. A delegate built from an instance method stores two pieces of information: - **`Delegate.Method`** — the method to call (`OnSettingsChanged`); - **`Delegate.Target`** — the object to call it on, which here is the window itself. The `add` accessor then combines that delegate into the service's existing delegate, producing a new **invocation list** that is stored back in the service's field. Nothing is stored in the window. The window only *used* its reference to the service to call the accessor. ## The direction of the reference Garbage collection in .NET keeps an object alive while it is **reachable** from a root (a static field, a local on a running thread, and so on). After the subscription, the reachability chain is: 1. something long-lived holds the settings service; 2. the service's `Changed` field holds the multicast delegate; 3. the delegate's `Target` holds the window; 4. the window holds its controls, its document buffer and whatever else it owns. So the **publisher keeps the subscriber alive**, never the reverse. That is why the official C# guide on subscribing tells you to unsubscribe before you dispose of a subscriber: until you do, the publisher's multicast delegate references the subscriber's handler, and garbage collection will not delete the subscriber. | Publisher lifetime | Subscriber lifetime | Outcome if nobody calls `-=` | |---|---|---| | Long (app-wide service) | Short (a window) | **Leak**: every closed window stays reachable | | `static` event | Anything | **Worst case**: the field lives as long as its type is loaded | | Short (a request, a dialog's own button) | Long (a logger) | Harmless: the publisher dies and takes its list with it | | Same object graph (a view and a child it owns) | Same | Harmless: they become unreachable together | ## Lambdas and captured variables A lambda handler changes *what* the delegate's `Target` is, not the direction: - a lambda that uses `this` or instance members compiles to a method on the window's class, so `Target` is the window; - a lambda that captures locals compiles to a method on a **compiler-generated closure class**; `Target` is that closure object, which holds the captured variables, and if one of them is the window, the window is reachable through it; - a lambda that captures nothing at all compiles to a method on a compiler singleton whose delegate is cached, so it holds nothing of the window. Either way, the service is still the object holding the chain. Method-group handlers are no safer than lambdas here: an instance method group always records its receiver. ## Static events A `static event` is backed by a static field. A static field is reachable for as long as its type is loaded, which for an ordinary application is the whole process. There is no publisher instance that can die and release the list, so every subscriber that forgets `-=` lives until the process ends. This is why many teams treat static events as a code smell for anything a short-lived object subscribes to. ## How to reason about it in an interview - Name the direction first: **publisher → delegate → subscriber**. - Then compare lifetimes: the leak needs a publisher that outlives its subscribers. - Then name the fix: call `-=` with an equal delegate when the subscriber's life ends, typically in its `Dispose` or close handler, or let the subscriber hold a subscription object it disposes. Whether you could instead use a weak reference is a separate design question with real trade-offs. A common trap is to describe this as "events leak". They do not; a subscription is just a strong reference stored in the publisher. Whether that reference becomes a leak depends entirely on which of the two objects is supposed to outlive the other. ## Seeing it for yourself You can observe the reference without any tooling. `GetInvocationList()` on the event's delegate, called from inside the publisher, returns one `Delegate` per handler, and each one exposes `Target` and `Method`. In the snippet below, the first entry's `Target` is the very window object that subscribed, and its `Method` is `OnSettingsChanged`. That one property is the whole leak in miniature: as long as the service keeps that delegate, the window cannot be collected. Two consequences follow for everyday code: - **Unsubscribing is the subscriber's job, but the publisher's lifetime decides whether it matters.** Code reviewers should ask "does this publisher outlive the subscriber?" for every `+=` they see. - **Removing the handler needs an equal delegate.** `settings.Changed -= OnSettingsChanged;` works because the new delegate has the same `Target` and `Method`; how a second, separately written lambda fails that test is a topic of its own.
- What changes if the settings service exposes its Changed event as a static event?The invocation list then lives in a static field, which stays reachable as long as its type is loaded, normally the whole process. No service instance can become unreachable and release it, so every subscriber that never calls `-=` is kept alive until the process ends. That makes a forgotten unsubscribe on a static event the worst version of this leak.
- If the window subscribes with a lambda that captures a local variable, what does the service hold?The delegate's `Target` becomes a compiler-generated closure object that stores the captured variables, and the method is generated on that closure class. The service holds the closure, and the closure holds whatever it captured; if it captured the window, the window stays reachable exactly as with a method group. Only a lambda that captures nothing holds no reference to the window.
A subscription is like leaving your phone number on a club's mailing list: the club keeps your number, not the other way round, and you stay on the list until you ask to be taken off.
- Subscribing to an event keeps the publisher alive, so the subscriber is safe.
- The garbage collector removes handlers whose subscriber is no longer used anywhere else.
- C# events hold their subscribers through weak references.
- Method-group handlers hold no reference to the object; only lambdas do.
- Every event subscription that is never removed is a memory leak.