Skip to content
AgileLogics
5 min read

Delegates & Events

Prerequisites: Collections in depth

A delegate is a type-safe reference to a method — C#'s equivalent of a function pointer (C) or a functional interface (Java), used constantly for callbacks.

delegate int Operation(int a, int b);

int Add(int a, int b) => a + b;
int Subtract(int a, int b) => a - b;

Operation op = Add;
Console.WriteLine(op(5, 3)); // 8

op = Subtract;
Console.WriteLine(op(5, 3)); // 2

An event is a delegate with restricted access — only the declaring class can raise it, but any number of outside listeners can subscribe:

class Button {
    public event Action? Clicked;

    public void Click() => Clicked?.Invoke();
}

var button = new Button();
button.Clicked += () => Console.WriteLine("Clicked!");
button.Click(); // Clicked!