How do you declare and raise a C# event that follows the EventHandler<TEventArgs> convention, and what goes in sender and e?
answer
- two parameters, void return
- object sender, data object e
- EventArgs.Empty when there is no data
- protected virtual OnPriceChanged
basics
~10 sDeclare 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 sThe .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 linesvar 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
Recall the shape: void handler, object sender, data object e, EventHandler<T> for data and EventArgs.Empty when there is none.
Explain why the protected virtual OnPriceChanged exists, why sender is this, and why the data class has read-only properties.
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.
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.