c# · level 3 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
One listener leaves. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
var bell = new Doorbell();
Action<string> log = who => Console.WriteLine($"Log: {who}");
bell.Rang += log;
bell.Rang += who => Console.WriteLine($"Ding for {who}");
bell.Ring("Sam");
bell.Rang -= log;
bell.Ring("Mo");
class Doorbell
{
public event Action<string> Rang;
public void Ring(string who) => Rang?.Invoke(who);
}
your turn
Your turn. Listen to the scoreboard.
On line 5, subscribe a handler that takes the team and its total, then prints one line using both. Word it your own way.
output
press run to see what happens
fix it
The oven crashes when the food is ready. Can you fix it?
output
press run to see what happens
- It crashes with
NullReferenceExceptionon line 14. Who has subscribed toReady? - Nobody subscribed, so the event is
null, and callingInvokeonnullcrashes. - Change
Ready.Invoke(food)toReady?.Invoke(food), then run.
nailed it
your objects can announce news now. :D
- An
eventlets outsiders subscribe but never call it. - Subscribe with
+=, and leave with-=. - Raise it with
?.Invokein case nobody is listening.
new words in your collection
- event
- subscribe
- handler
This lesson isn’t saved. A free account remembers every lesson you finish.