Events

An event in a class

An event is a delegate field with a restriction: code outside the class may only add and remove handlers, and only the class itself may raise it. The BCL shape is EventHandler: void Handler(object? sender, EventArgs e), or EventHandler<T> when the event carries data.

var counter = new Counter(); counter.Changed += (sender, value) => Console.WriteLine($"changed to {value}"); counter.Changed += OnChanged; counter.Increment(); counter.Increment(); counter.Changed -= OnChanged; counter.Increment(); Console.WriteLine($"value: {counter.Value}"); static void OnChanged(object? sender, int value) => Console.WriteLine($"handler two: {value}"); class Counter { public event EventHandler<int>? Changed; public int Value { get; private set; } public void Increment() { Value++; Changed?.Invoke(this, Value); } }

dotnet run

changed to 1
handler two: 1
changed to 2
handler two: 2
changed to 3
value: 3

The order of the output is the story. Both handlers ran on the first increment, in the order they subscribed: Changed is a multicast delegate, a list of methods called one after another. The third increment printed only the lambda, because -= removed the named handler.

Changed?.Invoke(this, Value) is the raise: the ?. is there because the event is null until somebody subscribes, and invoking a null delegate throws.

Subscribe and unsubscribe

+= adds a handler to the end of the list and -= removes the first equal one. Two rules follow, and both surprise a beginner:

A class that raises an event may also give it a custom add and remove accessor, and a class that only passes the event of another object through exposes it with event EventHandler<T> Changed { add => inner.Changed += value; remove => inner.Changed -= value; }. The lesson on properties shows the same accessor shape for a value.

The leak of a missing -=

A publisher holds a reference to every subscriber in its delegate list. If the subscriber is a long-lived object and the publisher is short-lived, the subscription is fine; if the subscriber is short-lived and the publisher lives on, the publisher keeps the subscriber alive after everything else has let it go.

var counter = new Counter(); counter.Changed += OnChanged; counter.Changed += OnChanged; Console.WriteLine($"handlers: {counter.HandlerCount}"); counter.Changed -= OnChanged; Console.WriteLine($"handlers: {counter.HandlerCount}"); static void OnChanged(object? sender, int value) => Console.WriteLine($"saw {value}"); class Counter { public event EventHandler<int>? Changed; public int HandlerCount => Changed?.GetInvocationList().Length ?? 0; public void Increment() => Changed?.Invoke(this, 0); }

dotnet run

handlers: 2
handlers: 1

The same method subscribed twice sits twice in the invocation list, and one -= took one copy out. That is why a class that subscribes in a constructor and again after a reload calls its handler twice per event, and why the count is the first thing to print when an event fires more often than expected.

A subscription is a reference in both directions, so the publisher and the subscriber keep each other alive. A class that subscribes to something that outlives it must unsubscribe in its Dispose, and the part on resources shows where that call belongs; the part on the garbage collector measures whether a listener survived a collection.

Exercises

  1. Subscribe the same named method twice and increment once. How many lines print, and what does one -= leave?
  2. Try to raise the event from outside the class. Read the error.
  3. Give the event an EventArgs subclass with a message and raise it with that payload.
  4. Remove the ?. from Invoke and increment before anybody subscribes. What happens?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What may code outside the class do with its event?

    Answer

    Add and remove handlers, but not raise it

    The event keyword restricts the field to += and -= from outside, so only the declaring class can invoke it.

  2. In which order do the handlers of one event run?

    Answer

    The order they were added

    The event is a multicast delegate whose invocation list keeps the subscription order.

  3. What does this program print? var counter = new Counter(); counter.Changed += (s, v) => Console.WriteLine($"a {v}"); counter.Changed += (s, v) => Console.WriteLine($"b {v}"); counter.Increment(); Console.WriteLine("done"); class Counter { public event EventHandler<int>? Changed; public void Increment() => Changed?.Invoke(this, 1); }

    Answer

    a 1 / b 1 / done

    The two lambdas were added in order, and Invoke calls them in that order.

  4. Why does the raise use Changed?.Invoke(...)?

    Answer

    The event is null until a handler is added, and invoking null throws

    A delegate field is null before the first +=, so the null check is what keeps the raise safe.

  5. What does removing a lambda written a second time do?

    Answer

    Nothing, because the two lambdas are different delegate objects

    Delegate equality compares the target and the method, and each lambda expression is its own generated method.

  6. What is the risk of a subscription that is never removed?

    Answer

    The publisher keeps the subscriber alive as long as it lives

    The publisher holds the delegate list, and the list holds a reference to every subscriber object.

  7. What does this program print? var counter = new Counter(); counter.Changed += (s, v) => Console.WriteLine("one"); counter.Increment(); class Counter { public event EventHandler<int>? Changed; public void Increment() => Changed?.Invoke(this, 0); }

    Answer

    one

    One handler is subscribed, so the raise calls it once and the lambda prints its line.

  8. Which pair of methods adds and removes a handler?

    Answer

    += and -=

    An event uses the delegate combination and removal operators, which are += and -=.

  9. What does an EventHandler<T> handler receive?

    Answer

    The sender and a value of type T

    The generic form carries a payload of type T as the second argument, next to the sender.

  10. Why must a class that subscribes to a long-lived publisher unsubscribe?

    Answer

    Because its Dispose is the only place that knows when it is done

    Only the subscriber knows when it no longer wants the calls, and leaving the reference behind keeps it alive.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev