skip to content

In C#, why does settings.Changed -= (s, e) => window.Refresh() fail to remove the handler that an identical lambda added with +=?

level: middleimportance: must knowfreq 65%

answer

  1. two lambdas, two methods
  2. delegate equality
  3. Target plus Method
  4. Delegate.Remove finds no match
  5. keep the instance you added

basics

~20 s

Each lambda expression compiles to its own method, so the lambda written after -= is a different delegate from the one added. Delegate.Remove finds no equal entry and silently leaves the list unchanged; store the delegate and remove that instance.

solid answer

~40 s

The compiler gives every lambda expression its own generated method, even when two bodies are character-for-character identical, and a capturing lambda also gets a closure object as its `Target`. Delegates compare equal only when their `Target` and `Method` match, and a field-like event's `-=` removes with `Delegate.Remove`, which searches the invocation list from the end for an equal entry. Nothing matches, so `Remove` returns the list unchanged: no exception, no compiler warning, and the handler, with everything it captured, stays attached. The fix is to keep the delegate you added, in a field or local, and pass that same instance to `-=`, or to subscribe with a method group such as `window.OnSettingsChanged`, which produces an equal delegate each time you write it.

code

csharp · 27 lines
csharp
var settings = new SettingsService();
var window = new DocumentWindow();

settings.Changed += (s, e) => window.Refresh();
settings.Changed -= (s, e) => window.Refresh();   // a different delegate: removes nothing
Console.WriteLine(settings.HandlerCount);          // 1

EventHandler handler = (s, e) => window.Refresh();
settings.Changed += handler;
settings.Changed -= handler;                       // same instance: removed
Console.WriteLine(settings.HandlerCount);          // still 1, the first lambda

settings.Changed += window.OnSettingsChanged;      // method group
settings.Changed -= window.OnSettingsChanged;      // new delegate, equal Target + Method
Console.WriteLine(settings.HandlerCount);          // 1

class SettingsService
{
    public event EventHandler? Changed;
    public int HandlerCount => Changed?.GetInvocationList().Length ?? 0;
}

class DocumentWindow
{
    public void Refresh() { }
    public void OnSettingsChanged(object? sender, EventArgs e) => Refresh();
}

go deeper

for a junior

Remember the rule: a lambda written again at -= is a new delegate, so keep the handler in a variable or use a method group if you will need to unsubscribe.

for a middle

Explain delegate equality by Target and Method, how Delegate.Remove searches the list from the end, and why a miss is silent.

for a senior

Connect a silent -= miss to a long-lived publisher retaining closures, and spot the pattern in review: subscribe and unsubscribe sites that each write their own lambda.

for a principal

Decide whether the codebase should ban inline lambda subscriptions to long-lived events, or require a subscription object that owns the exact delegate it removes.

## What the compiler does with each lambda A **lambda expression** such as `(s, e) => window.Refresh()` is not a value the runtime can compare by its text. The compiler lowers every lambda expression in the source into a **separate generated method**: - a lambda that uses only `this` becomes a private instance method on the enclosing class; - a lambda that captures locals or parameters becomes a method on a **compiler-generated closure class**, and each evaluation uses the closure object of the scope it runs in; - a lambda that captures nothing becomes a method on a compiler singleton, and its delegate is cached in a static field. Writing the same lambda twice therefore produces two methods. In the run behind this answer, two identical `EventHandler` lambdas compiled to methods named `<<Main>$>b__0_0` and `<<Main>$>b__0_1`, and `a.Equals(b)` printed `False`. ## How `-=` decides what to remove For a field-like event, `-=` calls the event's `remove` accessor, which uses `Delegate.Remove(source, value)`. The runtime source for multicast delegates walks the invocation list **backwards** looking for an entry that is equal to `value`, where delegate equality means: | Compared part | Must match | |---|---| | Delegate type | yes (a mismatch makes `Delegate.Remove` throw `ArgumentException`) | | `Method` | the same method | | `Target` | the same object, or both null for a static method | If an equal entry is found, `Remove` returns a new delegate without it (or `null` when it was the last one). If none is found, it **returns the original list unchanged**. There is no exception and the compiler issues no warning, so a broken unsubscribe compiles cleanly and fails silently. ## Why it matters for leaks A silently failed `-=` means the handler is still in the publisher's list. If the publisher is long-lived, its delegate keeps the handler's `Target` alive: the window for a lambda that used `this`, or the closure object and everything it captured. So the window you thought you had detached stays reachable, and its `Refresh` keeps running on every raise. ## Three ways to make removal work 1. **Store the delegate.** Assign the lambda to a field or local (`EventHandler handler = (s, e) => window.Refresh();`), then use `+= handler` and `-= handler`. Both operations see the very same instance. 2. **Use a method group.** `settings.Changed -= window.OnSettingsChanged;` creates a *new* delegate object, but it is equal to the one added, because its `Target` is the same window and its `Method` is the same method. 3. **Return a subscription object.** A `Subscribe` method that returns `IDisposable` can capture the delegate it added and remove exactly that instance when disposed, so callers never have to recreate it. ## Edge cases worth knowing - **The same lambda site evaluated twice can compare equal.** A helper `EventHandler Make() => (s, e) => Refresh();` that captures only `this` yields equal delegates on every call, because the method and the `Target` are the same; a non-capturing lambda returns the same cached instance. The failure comes from writing the lambda a second time at the `-=` site, not from lambdas as such. - **Subscribing twice needs two removals.** `Delegate.Remove` removes only the last matching entry, so `+= handler` twice followed by one `-= handler` leaves one copy (the run printed a count of 1). `Delegate.RemoveAll` removes every match, but an event's `-=` does not use it. - **Outside code cannot clear the event.** Assigning `settings.Changed = null` from another class fails with CS0070, "The event 'SettingsService.Changed' can only appear on the left hand side of += or -= (except when used from within the type 'SettingsService')". ## Spotting it in review The defect has a recognisable shape: a constructor or `OnLoaded` method that writes `service.Changed += (s, e) => ...;` and a `Dispose` or close handler that writes the same lambda again after `-=`. Both lines compile, the code reads symmetrically, and the bug is invisible until memory grows. Useful review questions: - Is the delegate passed to `-=` the *same instance*, or at least an *equal* method-group delegate, as the one passed to `+=`? - Does the lambda capture `this` or a large local, so that a failed removal keeps the subscriber and its state alive? - Is the publisher longer-lived than the subscriber? If not, a missing `-=` is harmless and may not be worth the ceremony. Microsoft's own guide states the practical rule: if you will need to unsubscribe, do not subscribe with an anonymous function, or store it in a delegate variable first.

  • Why does -= with a method group work, when each use of window.OnSettingsChanged creates a new delegate object?
    `Delegate.Remove` looks for an *equal* entry, not the same object. Two delegates built from the same instance method on the same receiver have the same `Target` and the same `Method`, so they compare equal and the earlier one is removed. A lambda written at the `-=` site has a different generated `Method`, so it never compares equal.
  • A handler was added twice with += handler. What does a single -= handler leave in the event?
    One copy. `Delegate.Remove` searches the invocation list from the end and removes only the last matching entry, so the handler still runs once per raise. You need a second `-= handler` to remove it completely. `Delegate.RemoveAll` would remove every match, but an event's remove accessor does not call it.

  • Two lambdas with the same body are the same delegate, so -= removes the first.
  • A failed -= throws an exception, so a broken unsubscribe is easy to spot.
  • The compiler warns when a lambda passed to -= can never match.
  • Lambda handlers can never be removed from a C# event.
  • One -= removes every copy of a handler that was added more than once.