Delegates and EventHandler

Every WinForms handler is an ordinary .NET delegate, and the events of the controls are ordinary .NET events. This lesson takes the mechanism apart away from the controls, because a form is a bad place to learn what += does: the code is the same, and the version without a window runs on this machine.

A delegate is a method value

A delegate type is a signature: a delegate declaration names the parameters and the return type a method must have to be used as a value of that type. Action and Func are generic delegates the base library already declares, and a method group converts to one of them:

using System; Action<string> print = Console.WriteLine; Func<int, int, int> add = (a, b) => a + b; print($"sum: {add(2, 3)}"); Console.WriteLine($"method: {print.Method.Name}"); Console.WriteLine($"static: {print.Method.IsStatic}");

dotnet run

sum: 5
method: WriteLine
static: True

The output is the real run. Console.WriteLine as a method group became an Action<string>, and the lambda became a Func<int, int, int>. Method is the method the delegate points at, which the run printed as WriteLine, and IsStatic is true because Console.WriteLine is a static method. A delegate to an instance method reports IsStatic = false and a Target that is the object it will be called on, which is the difference that makes a handler keep a form alive.

A delegate is a value, so it can be passed to a method, stored in a field and returned. That is the whole of what an event is built on.

An event

An event is a delegate field with a rule: code outside the class may only += and -=, never invoke it and never assign it. That is why a form cannot raise a control's Click, and why a model that raises its own event can.

using System; using System.Collections.Generic; var order = new Order("A-1041"); order.Changed += (sender, e) => Console.WriteLine($"log: {e.Field} = {e.Value}"); order.Changed += (sender, e) => Console.WriteLine($"screen: {e.Field}"); EventHandler<ChangedEventArgs> audit = (sender, e) => Console.WriteLine($"audit: {e.Field}"); order.Changed += audit; order.Set("status", "paid"); order.Changed -= audit; order.Set("status", "shipped"); Console.WriteLine($"handlers: {order.HandlerCount}"); internal sealed class ChangedEventArgs : EventArgs { public ChangedEventArgs(string field, string value) { Field = field; Value = value; } public string Field { get; } public string Value { get; } } internal sealed class Order { private readonly Dictionary<string, string> _fields = new(); public Order(string id) => Id = id; public string Id { get; } public event EventHandler<ChangedEventArgs>? Changed; public int HandlerCount => Changed?.GetInvocationList().Length ?? 0; public void Set(string field, string value) { _fields[field] = value; Changed?.Invoke(this, new ChangedEventArgs(field, value)); } }

dotnet run

log:    status = paid
screen: status
audit:  status
log:    status = shipped
screen: status
handlers: 2

The output is the real run, and it is the shape of every event in WinForms. EventHandler<T> is the generic form of the EventHandler that Click uses, and the EventArgs subclass carries what the handler needs. The sender is the object that raised the event, which is how one handler serves several controls. Changed?.Invoke is the whole raise: the null-conditional call does nothing when nobody subscribed, which is why an event is always declared nullable in a class that raises it.

Order and exceptions

A delegate that has been += twice is a multicast delegate, and invoking it calls the methods in subscription order. An exception in one of them stops the chain and propagates, so the handlers after it never run:

using System; Action chain = () => Console.WriteLine("first"); chain += () => throw new InvalidOperationException("second"); chain += () => Console.WriteLine("third"); try { chain(); } catch (InvalidOperationException error) { Console.WriteLine($"stopped at: {error.Message}"); } Console.WriteLine($"handlers in the chain: {chain.GetInvocationList().Length}");

dotnet run

first
stopped at: second
handlers in the chain: 3

The output is the real run. Three handlers were subscribed, two of them ran, and the third did not, because the second threw. In a form this is the rule behind a Click handler that throws: the exception reaches the message loop, which shows the unhandled-exception dialog, and the handlers after it in the chain are skipped. GetInvocationList() is how a class counts or calls its subscribers one at a time, and it is the answer to "continue after a failing handler" as well: enumerate the list and put a try inside the loop.

Unsubscribing

A handler added with += stays attached until the object that holds it is collected. -= removes exactly one subscription, and it compares the delegate by target and method, so the same lambda written twice does not remove anything:

Two smaller rules follow from the mechanics. Subscribing the same handler twice calls it twice, which is a common bug in a Load handler that runs again after the form is shown. And raising an event from a getter or a constructor hands the subscribers a half-built object, which is why a model raises after its state is consistent.

Exercises

  1. Add a fourth handler that throws to the Order program, run it, and explain which lines disappear.
  2. Change HandlerCount to return the method names, and print them after the unsubscription.
  3. Store a lambda in an EventHandler variable, subscribe it twice and unsubscribe once, and print the count.

Questions

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

  1. What can code outside the class do with an event?

    Answer

    Subscribe and unsubscribe, but not invoke it

    The event keyword restricts access to += and -=, which is why a form cannot raise Click.

  2. Which type does a Click handler have?

    Answer

    EventHandler: void (object? sender, EventArgs e)

    Click passes no data beyond EventArgs, so the non-generic EventHandler is enough.

  3. What is the sender parameter?

    Answer

    The object that raised the event

    It is how one handler serves several controls.

  4. In which order does a multicast delegate call its handlers?

    Answer

    The order they were subscribed

    The run printed log, screen, audit in subscription order.

  5. What happens when one handler of a multicast invocation throws?

    Answer

    The rest are skipped and the exception propagates

    The run showed first, then the exception, and never third.

  6. What does Changed?.Invoke do when nobody subscribed?

    Answer

    Nothing, because the delegate is null

    The null-conditional call is the standard way to raise an event safely.

  7. Why does the same lambda written twice not unsubscribe with -=?

    Answer

    Each lambda is a different delegate instance

    Removal compares target and method, so the lambda must be stored to be removed.

  8. What did the run print after the audit handler was removed?

    Answer

    log and screen only

    The second Set printed two lines, and the count was 2.

  9. What is GetInvocationList() for?

    Answer

    To call or count the subscribers one at a time

    It is how a class continues after a failing handler, or reports who listens.

  10. Why is an event declared as a nullable delegate in a class that raises it?

    Answer

    Because it is null until the first subscriber

    The null-conditional raise depends on it, and Nullable annotations make that explicit.

Every listing on this page is plain .NET code with no window in it: it was built and run with the .NET SDK 10.0.303 on Alpine Linux 3.24.3 (x86_64) in a Docker container, and the output printed below each program is that run. The WinForms pages of this course are built for net10.0-windows against Microsoft.WindowsDesktop.App.Ref 10.0.15 and never run on Linux: WinForms needs Windows.

Article author: Arthur Isaev