Beep!Flash!Flash!oven · Ovenevent DoneDone [0]–Done [1]–Beep()Flash()1var oven = new Oven();2oven.Done += Beep;3oven.Done += Flash;4oven.Bake();5oven.Done -= Beep;6oven.Bake();1public event Action? Done;2public void Bake() =>3 Done?.Invoke();newBeepFlashcallBeep!Flash!CS0070
Front row: the code (Program.cs and class Oven)Back row: the oven object, its invocation list, the handlers and the consoleTokens: delegates joining and leaving the list, calls, and printed textBack row: the console, the oven object with its event Done drawn as a two-place invocation list, and the handler methods Beep() and Flash(). Front row: Program.cs, which subscribes and unsubscribes, and class Oven, which declares the event and raises it in Bake. += puts a handler into the list, Bake calls every handler in list order, -= takes one out; the program prints Beep!, Flash!, Flash!. Delegates never change. Each += makes a new delegate with a longer invocation list (Delegate.Combine) and stores it in the event; each -= makes a new, shorter one (Delegate.Remove). The figure shows the list being edited in place.

Declare an event

  1. An event lets an object tell other code that something happened. The object that raises the event is the publisher; here, an oven that finishes baking. Methods that want the news are subscribers, also called event handlers.

Subscribe

Raise

Unsubscribe and rules

What happens

// step 1/10 · news
publisher    the object that raises the event   (oven)
event        the news: "baking is done"         (Done)
subscribers  methods that react: handlers       (Beep, Flash)
the publisher never needs to know who is listening

Delegates never change. Each += makes a new delegate with a longer invocation list (Delegate.Combine) and stores it in the event; each -= makes a new, shorter one (Delegate.Remove). The figure shows the list being edited in place. Most .NET events follow a standard pattern: the type EventHandler or EventHandler<TEventArgs>, and handlers with two parameters, sender (who raised it) and e (the event data). Action is used here to keep the example short.