×

c# · level 3 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An lets an object announce news to whoever listens.

Sometimes an object must tell others that something happened, like a parcel moving or stock running low, without knowing who cares. An event is a delegate field marked event. Outside code may only add or remove methods, never call it or wipe it.

Listeners with +=, handing over a : the method or lambda to run. They leave with -=. The owner raises the event with Moved?.Invoke(place), and every handler runs in the order it subscribed.

The ?. matters: with no subscribers, the event is null.

using System;

var parcel = new Parcel();
parcel.Moved += place => Console.WriteLine($"App: now at {place}");
parcel.Moved += place => Console.WriteLine($"Text: your parcel is at {place}");
parcel.MoveTo("the depot");
parcel.MoveTo("your door");

class Parcel
{
    public event Action<string> Moved;

    public void MoveTo(string place)
    {
        Moved?.Invoke(place);
    }
}

Parcel never mentions apps or texts, so new listeners can join without changing it.