C# Intermediate: OOP, Interfaces & Events

Lesson 5 of 7

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, one string parameter) can be assigned to it.
  • event Notify OnTriggered; exposes a delegate as an event, code outside Alarm can subscribe (+=) or unsubscribe (-=), but can't invoke it directly or overwrite other subscribers, only Alarm itself can call Invoke.
  • ?.Invoke(...) safely calls every subscribed method, and does nothing if nobody has subscribed yet (OnTriggered would be null).
  • 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.

📝 Delegates & Events Quiz

Passing score: 70%
  1. 1.What does the event keyword restrict, compared to a plain public delegate field?

  2. 2.Subscribing to an event uses the ____ operator, unsubscribing uses -=.

  3. 3.Multiple methods can subscribe to the same event.