Delegates and Events
A delegate is a type-safe reference to a method, it lets you pass a method around like a value, store it in a variable, and call it later.
delegate void Notify(string message);
class Alarm
{
public event Notify OnTriggered;
public void Trigger()
{
Console.WriteLine("Alarm triggered!");
OnTriggered?.Invoke("Intruder detected");
}
}
class Program
{
static void Main()
{
var alarm = new Alarm();
alarm.OnTriggered += message => Console.WriteLine($"Security notified: {message}");
alarm.OnTriggered += message => Console.WriteLine($"Logged: {message}");
alarm.Trigger();
}
}
The pieces
delegate void Notify(string message);declares a delegate type, any method matching that signature (void, onestringparameter) can be assigned to it.event Notify OnTriggered;exposes a delegate as an event, code outsideAlarmcan subscribe (+=) or unsubscribe (-=), but can't invoke it directly or overwrite other subscribers, onlyAlarmitself can callInvoke.?.Invoke(...)safely calls every subscribed method, and does nothing if nobody has subscribed yet (OnTriggeredwould benull).- Multiple methods can subscribe to the same event, they all run, in the order they were added, when it's invoked.
Why events instead of calling methods directly?
Events decouple the class raising them from whoever reacts to them: Alarm doesn't need to know that a security system or a logger exists, it just announces "something happened," and anything that cares can subscribe.