skip to content

When would you write custom add and remove accessors for a C# event, and what changes inside the class once you do?

level: middleimportance: should knowfreq 35%

answer

  1. property-like syntax for events
  2. you own the storage
  3. both accessors or neither
  4. CS0079 when raising by name

basics

~20 s

Write add and remove bodies when subscriptions need custom storage, forwarding, locking or bookkeeping. Then no backing field exists, so the class raises its own stored delegate, because using the event name for anything but += or -= is error CS0079.

solid answer

~30 s

Custom accessors look like a property with `add` and `remove` blocks, where `value` is the handler. You write them to forward subscriptions to an inner object, to store many sparse events in one `EventHandlerList`, to take a `lock` or log subscriptions, or because an explicit interface implementation of an event must use accessor syntax (CS0071). Both accessors are required (CS0065). Once you write them, the compiler generates no backing field and no synchronization, so inside the class `PriceChanged?.Invoke(...)` is error CS0079: you raise the field you declared yourself, and thread safety is your job.

code

csharp · 21 lines
csharp
var ticker = new StockTicker();
EventHandler<decimal> h = (s, p) => Console.WriteLine($"dashboard: {p}");
ticker.PriceChanged += h;
ticker.Update(410m);
ticker.PriceChanged -= h;
ticker.Update(411m);   // no subscribers left: nothing printed

class StockTicker
{
    private readonly object _gate = new();
    private EventHandler<decimal>? _priceChanged;   // the storage is yours now

    public event EventHandler<decimal>? PriceChanged
    {
        add { lock (_gate) { _priceChanged += value; Console.WriteLine("subscribed"); } }
        remove { lock (_gate) { _priceChanged -= value; Console.WriteLine("unsubscribed"); } }
    }

    // PriceChanged?.Invoke(...) here would be error CS0079: raise the field instead
    public void Update(decimal price) => _priceChanged?.Invoke(this, price);
}

go deeper

for a junior

Recognise the syntax: an event with add and remove blocks, where value is the handler, used exactly like any other event by subscribers.

for a middle

Explain the compiler rules: both accessors required (CS0065), no backing field, so raising goes through your own field (CS0079 otherwise).

for a senior

Justify each use case, forwarding, EventHandlerList storage, lazy upstream work, and check that the bodies are synchronized and symmetrical.

for a principal

Treat custom accessors as an exception that needs a reason in review, since they trade generated thread safety and readability for control.

## The syntax Most events are **field-like**: `public event EventHandler<decimal>? PriceChanged;`, for which the compiler generates a backing field and the `add` and `remove` accessors. An event can instead declare the accessors itself, using syntax that resembles a property: ```csharp private EventHandler<decimal>? _priceChanged; public event EventHandler<decimal>? PriceChanged { add { lock (_gate) { _priceChanged += value; } } remove { lock (_gate) { _priceChanged -= value; } } } ``` Inside each accessor, `value` is the handler being added or removed. Subscribers do not notice the difference: they still write `ticker.PriceChanged += handler` and `-=`, which call these bodies. ## Rules the compiler enforces 1. **Both accessors or neither.** Declaring only `add` is CS0065: "event property must have both add and remove accessors". 2. **No initializer.** An event with accessor bodies cannot be followed by `= null`; the parser rejects it (CS1519), because there is no field to initialize. 3. **No raising by name.** Inside the class, using `PriceChanged` for anything except `+=` and `-=` is CS0079: "The event 'StockTicker.PriceChanged' can only appear on the left hand side of += or -=". There is no backing field for the name to bind to, so the class raises the delegate it stores itself, `_priceChanged?.Invoke(this, price)`. 4. **Explicit interface implementations require them.** Implementing `event EventHandler? ITicker.PriceChanged;` without accessor bodies is CS0071: "An explicit interface implementation of an event must use event accessor syntax". ## Reasons to write them | Reason | What the accessors do | |---|---| | Forwarding | pass `value` on to an inner component's event, so subscribers attach to the real source | | Sparse storage | store handlers in one `System.ComponentModel.EventHandlerList` keyed by an object per event, instead of one field per event | | Synchronization | take a `lock` or use your own compare-and-swap, for example to update other state atomically with the list | | Side effects | start an upstream feed on the first subscriber and stop it after the last one leaves | | Logging or diagnostics | record who subscribes, or reject duplicate subscriptions | | Explicit interface implementation | required by CS0071, often to map two interfaces' events of the same name | **Sparse storage** matters for classes that expose dozens of events, most of which nobody subscribes to: one `EventHandlerList` costs less than dozens of null fields per instance. Its `AddHandler(key, value)`, `RemoveHandler(key, value)` and indexer `this[key]` do the bookkeeping, and the class raises with `(list[key] as EventHandler)?.Invoke(this, e)`. **Lazy upstream work** is the common modern reason: a ticker that opens a market-data subscription only while at least one dashboard listens can start it in `add` when the stored delegate goes from `null` to non-null, and stop it in `remove` when it returns to `null`. ## What you give up - **Generated thread safety.** The compiler's accessors for a field-like event use `Interlocked.CompareExchange` so concurrent subscriptions are never lost. Custom bodies are plain code: `add => _priceChanged += value;` without a lock can lose subscriptions under concurrency. - **Brevity and convention.** Every raise site uses the private field, and readers must check the accessors to know what `+=` does. - **Simple debugging.** Subscriptions that are forwarded to another object live on that object; a subscriber leak then has to be traced through the forwarding. ## A practical rule Stay with field-like events unless one of the reasons in the table applies. When you do write accessors, keep them short, synchronize them, keep the raise outside any lock by invoking a snapshot of the field, and make `remove` the exact inverse of `add`, including any side effects.

  • How would a C# event with custom accessors start a market-data feed only while someone is subscribed?
    Inside a lock, `add` combines `value` into the private field and starts the feed when the field goes from `null` to non-null; `remove` takes `value` out and stops the feed when the field returns to `null`. Because both run under the same lock, a subscribe and an unsubscribe racing each other cannot leave the feed running with no listeners.
  • Why must an explicit interface implementation of an event use custom accessors?
    The language only allows the accessor form there: `event EventHandler? ITicker.PriceChanged;` is CS0071, "An explicit interface implementation of an event must use event accessor syntax". The bodies usually forward to a private field or to another event, which is also how a class maps two interfaces that both declare an event with the same name.

  • A custom add accessor can be declared on its own without a remove.
  • With custom accessors, the class can still raise the event by its name.
  • Custom accessors get the same compiler-generated thread safety as field-like events.
  • Subscribers must call AddHandler explicitly when an event has custom accessors.
  • Custom accessors change how subscribers write += and -=.