skip to content

EventHandler Conventions

event limits a delegate field to += and -= outside its class, and EventHandler<T> is the standard shape. Interviewers ask how to raise an event safely across threads.

on this pageshow

questions

5

How do you declare and raise a C# event that follows the EventHandler<TEventArgs> convention, and what goes in sender and e?

level: juniorimportance: must knowfreq 65%

answer

  1. two parameters, void return
  2. object sender, data object e
  3. EventArgs.Empty when there is no data
  4. protected virtual OnPriceChanged

basics

~10 s

Declare event EventHandler<PriceChangedEventArgs>? PriceChanged, raise it from a protected virtual OnPriceChanged method with PriceChanged?.Invoke(this, e): sender is the publisher, e carries the data, and EventArgs.Empty stands in when there is none.

solid answer

~30 s

The .NET convention is a `void` handler with two parameters, `object? sender` and `TEventArgs e`, so you declare `public event EventHandler<PriceChangedEventArgs>? PriceChanged;` rather than a custom delegate type. The data goes in an immutable class, conventionally derived from `EventArgs`, with read-only properties such as `OldPrice` and `NewPrice`. An event with no data uses plain `EventHandler` and passes `EventArgs.Empty`. The class raises it from `protected virtual void OnPriceChanged(PriceChangedEventArgs e) => PriceChanged?.Invoke(this, e);`, passing `this` as sender, so a subclass can raise or intercept it, and `?.` skips the call when nobody subscribed.

code

csharp · 30 lines
csharp
var ticker = new StockTicker("MSFT");
ticker.PriceChanged += (sender, e) =>
    Console.WriteLine($"{((StockTicker)sender!).Symbol}: {e.OldPrice} -> {e.NewPrice}");
ticker.Halted += (sender, e) => Console.WriteLine($"halted; e is EventArgs.Empty: {e == EventArgs.Empty}");
ticker.Update(410m);
ticker.Update(412m);
ticker.Halt();

class PriceChangedEventArgs(decimal oldPrice, decimal newPrice) : EventArgs
{
    public decimal OldPrice { get; } = oldPrice;
    public decimal NewPrice { get; } = newPrice;
}

class StockTicker(string symbol)
{
    private decimal _price;
    public string Symbol { get; } = symbol;
    public event EventHandler<PriceChangedEventArgs>? PriceChanged;
    public event EventHandler? Halted;

    public void Update(decimal price)
    {
        var old = _price;
        _price = price;
        OnPriceChanged(new PriceChangedEventArgs(old, price));
    }
    public void Halt() => Halted?.Invoke(this, EventArgs.Empty);
    protected virtual void OnPriceChanged(PriceChangedEventArgs e) => PriceChanged?.Invoke(this, e);
}

go deeper

for a junior

Recall the shape: void handler, object sender, data object e, EventHandler<T> for data and EventArgs.Empty when there is none.

for a middle

Explain why the protected virtual OnPriceChanged exists, why sender is this, and why the data class has read-only properties.

for a senior

Spot convention breaks in review: null event args, mutable data, a struct used for a Cancel flag, or a custom delegate type where EventHandler<T> fits.

for a principal

Weigh consistency against strictness: one event shape across a codebase makes every component learnable, at the cost of a small class per event.

## The shape every .NET event shares An **event** in C# is a member whose type is a delegate type; subscribers attach methods with `+=` and detach them with `-=`. You could declare any delegate type for it, but .NET libraries follow one shape so that every event looks familiar: ```csharp public delegate void EventHandler(object? sender, EventArgs e); public delegate void EventHandler<in TEventArgs>(object? sender, TEventArgs e); // abridged: the BCL also adds an allows ref struct clause ``` Both delegates live in the `System` namespace. The design guidelines say to use `EventHandler<TEventArgs>` instead of creating new delegate types, and they spell out the parts: - **`void` return.** An event can have zero, one or many subscribers, so no single return value makes sense. - **`sender`, typed `object`.** The object that raised the event, which lets one handler serve several publishers and talk back to the one that called it. - **`e`, the event data.** One object carrying everything the handler needs, so the signature never grows a third parameter. ## Declaring the data and the event For a stock-ticker class that tells dashboards about price changes: 1. Define the data class, conventionally named after the event plus `EventArgs`: `PriceChangedEventArgs` with read-only `OldPrice` and `NewPrice`. Make it a class with immutable properties, so one subscriber cannot change what the next one sees. 2. Declare `public event EventHandler<PriceChangedEventArgs>? PriceChanged;`. The `?` is the nullable annotation: the backing field is `null` until someone subscribes. 3. For an event with nothing to report, such as `Halted`, declare `public event EventHandler? Halted;` and raise it with `EventArgs.Empty`, the shared instance that means *no data*. Deriving from `EventArgs` is a convention, not a compiler rule: current .NET declares `EventHandler<TEventArgs>` with no constraint that `TEventArgs` derive from `EventArgs`, so `EventHandler<decimal>` compiles. The guidelines still recommend a subclass of `EventArgs` for public events, because a dedicated class can gain properties later without breaking subscribers, while a bare `decimal` or plain `EventArgs` cannot. ## Raising it: the On method | Part | Convention | Why | |---|---|---| | Raising method | `protected virtual void OnPriceChanged(PriceChangedEventArgs e)` | subclasses cannot invoke the base class's event directly (CS0070), so they call or override this | | Name | `On` followed by the event name | readers find the raise point instantly | | Parameter | one parameter, the event data | the guidelines ask for exactly one | | `sender` | `this` for an instance event; `null` for a static event | handlers can reach the publisher | | `e` | never `null`; `EventArgs.Empty` when there is no data | handlers can read `e` without a null check | | Body | `PriceChanged?.Invoke(this, e)` | reads the event's delegate once and skips the call when there are no subscribers | The guidelines limit the protected virtual method to non-static events on unsealed classes; a sealed class or a struct can raise the event from a private method instead. An override of `OnPriceChanged` may choose not to call the base implementation, so the base class should not put logic it depends on inside that method. ## Subscribing to it A subscriber writes a method or lambda whose signature matches: `void OnPrice(object? sender, PriceChangedEventArgs e)`. It attaches with `ticker.PriceChanged += OnPrice;` and detaches with `-=`. When the handler needs the publisher it casts `sender`, for example `((StockTicker)sender!).Symbol`. Handlers run synchronously, in the order they subscribed, on the thread that raised the event. ## Mistakes reviewers catch - A custom `delegate void PriceChangedHandler(decimal price)` where `EventHandler<T>` would do. - Passing `null` as `e`, or as `sender` on an instance event, which handlers are entitled to dereference. - Mutable properties on the data class, letting one subscriber rewrite what others see. The exception is a deliberate result flag such as a `Cancel` property, which needs a class so the publisher sees what subscribers set. - A struct as the data type for such a flag: each handler would get its own copy, and the publisher would never see the change. - Raising with `if (PriceChanged != null) PriceChanged(this, e);`, which reads the event's delegate twice; `?.Invoke` reads it once.

  • Must the TEventArgs of EventHandler<TEventArgs> derive from EventArgs in current .NET?
    No. The current declaration, `public delegate void EventHandler<in TEventArgs>(object? sender, TEventArgs e)` plus an `allows ref struct` clause, has no `EventArgs` constraint, so `EventHandler<decimal>` compiles. Deriving from `EventArgs` remains the guideline for public events because a dedicated class can gain properties later without breaking subscribers.
  • Why does the convention say to make the event data class immutable?
    Every subscriber receives the same object, one after another. If its properties are settable, an early subscriber can change `NewPrice` before later ones read it. Read-only properties guarantee all subscribers see what the publisher sent. A deliberate exception is a `Cancel` flag that subscribers set and the publisher reads after raising.

  • Every event needs its own custom delegate type.
  • Passing null for e is fine when the event carries no data.
  • Subclasses can raise a base class event directly, so OnXxx methods are pointless.
  • The event data type must derive from EventArgs or it will not compile.
  • An event handler should return a value to tell the publisher what happened.
open as a page

In C#, what does declaring PriceChanged with the event keyword change compared with exposing a public delegate field of the same type?

level: middleimportance: must knowfreq 72%

basics

~10 s

The event keyword limits code outside the declaring type to += and -=. A public delegate field also lets any caller overwrite every subscriber with = or null and raise the notification itself.

open as a page

In C#, why is if (PriceChanged != null) PriceChanged(this, e) unsafe when dashboards unsubscribe from other threads, and what fixes it?

level: seniorimportance: must knowfreq 60%

basics

~20 s

The check and the call read the event's backing field separately; if the last handler unsubscribes in between, the call hits null and throws NullReferenceException. PriceChanged?.Invoke(this, e) reads the field once and invokes that immutable delegate.

open as a page

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%

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.

open as a page

In C#, are += and -= on a field-like event thread-safe, and what does the compiler generate for its add and remove accessors?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Yes. The compiler-generated add and remove accessors build a new delegate with Delegate.Combine or Delegate.Remove and publish it with Interlocked.CompareExchange in a retry loop, so concurrent subscriptions are not lost. Hand-written accessors get none of that.

open as a page