Events and subscriptions
Events and subscriptions
A C# event lets an object announce a change without knowing what its listeners will do. The publisher owns the notification; subscribers attach compatible delegates. Unlike a public delegate field, an event does not let ordinary outside callers replace or invoke its backing delegate.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Publish a change
Declare an event with event EventHandler? Changed. The nullable delegate is initially empty. Call Changed?.Invoke(this, EventArgs.Empty) inside the publisher after a meaningful state change. The sender identifies the source; EventArgs.Empty means there is no additional payload.
using System;var shelf = new Shelf();int notices = 0;shelf.Changed += (_, _) => notices++;shelf.SetStock(4);shelf.SetStock(4);shelf.SetStock(2);Console.WriteLine(notices);class Shelf{ public int Stock { get; private set; } public event EventHandler? Changed; public void SetStock(int quantity) { if (quantity < 0) throw new ArgumentOutOfRangeException(nameof(quantity)); if (Stock == quantity) return; Stock = quantity; Changed?.Invoke(this, EventArgs.Empty); }}The initial change to 4 and the later change to 2 each raise one event. The repeated value does not. State is updated before subscribers run.
Expected output (reasoned, not executed):
2Pass meaningful event data
Use EventHandler<TEventArgs> when a notification needs details. A dedicated EventArgs subclass with get-only properties provides a clear payload contract. Subscribers need not cast the sender to read the quantity.
using System;var bin = new Bin();bin.Changed += (_, e) => Console.WriteLine($"{e.Before} -> {e.After}");bin.Update(3);bin.Update(8);class StockChange : EventArgs{ public int Before { get; } public int After { get; } public StockChange(int before, int after) { Before = before; After = after; }}class Bin{ private int quantity; public event EventHandler<StockChange>? Changed; public void Update(int next) { if (next < 0) throw new ArgumentOutOfRangeException(nameof(next)); if (next == quantity) return; int before = quantity; quantity = next; Changed?.Invoke(this, new StockChange(before, next)); }}Each event carries the earlier and current value; the event data is separate from the publisher. The constructor initializes get-only properties.
Expected output (reasoned, not executed):
0 -> 33 -> 8Understand synchronous delivery
A normal multicast delegate invocation calls handlers synchronously in invocation-list order. If a handler throws and the publisher does not isolate it, the exception escapes and later handlers are not called. This is not a transaction: changes before the event may remain committed.
using System;var bell = new Bell();bell.Rang += (_, _) => Console.WriteLine("first");bell.Rang += (_, _) => throw new InvalidOperationException("listener failed");bell.Rang += (_, _) => Console.WriteLine("third");try { bell.Ring(); }catch (InvalidOperationException) { Console.WriteLine("caught"); }class Bell{ public event EventHandler? Rang; public void Ring() => Rang?.Invoke(this, EventArgs.Empty);}The failing second handler interrupts the invocation; third never prints. Choose and document a failure policy rather than silently swallowing all exceptions.
Expected output (reasoned, not executed):
firstcaughtCommon mistakes and edge cases
An event is not a durable message queue or a promise of background execution. ?.Invoke avoids invoking a null delegate and evaluates its receiver once; it does not make publisher state, subscriber code, or unsubscription globally thread-safe. Avoid async void handlers unless required by the event signature: the publisher cannot await their completion through the event, and failures need an explicit handling policy.
Practice and recap
Extend Shelf so that a second handler records each stock change. Apply 0, 5, 5, 1, 0 starting from zero; verify notification count and final value. Try negative stock and confirm no notification.
Hint: Track distinct successive values; validate before assignment.
Learning objective: Describe publisher and subscriber responsibilities. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Events and subscriptions — knowledge check
Apply the lesson concepts to the following scenarios.
Who raises a field-like event?
Why use EventHandler<StockChange>?
Starting at zero, update to 2, 2, 3. How many Shelf notifications?
What happens after the second Bell handler throws?
What does ?.Invoke guarantee here?