16
Lesson 16 of 35 ยท OOP

Delegates & Events

Delegates are type-safe function pointers. Events build on delegates to provide a publish-subscribe communication model. Together they are the backbone of GUI programming, async patterns, and the Observer design pattern.

Delegates

A delegate type declares the signature of the methods it can point to. Action and Func are built-in generic delegates that cover most scenarios.

Delegates Delegates.cs
// Custom delegate
delegate int MathOp(int a, int b);

MathOp add = (a, b) => a + b;
MathOp mul = (a, b) => a * b;
Console.WriteLine(add(3, 4)); // 7
Console.WriteLine(mul(3, 4)); // 12

// Built-in delegates
Action print = Console.WriteLine;
Func power = (base_, exp) => (int)Math.Pow(base_, exp);

print("Hello");
Console.WriteLine(power(2, 10)); // 1024

Events

An event is a special delegate member that can only be invoked from within the declaring class. Subscribers add handlers with += and remove them with -=.

Event example Events.cs
public class Button
{
    public event EventHandler? Clicked;
    public void Click() => Clicked?.Invoke(this, EventArgs.Empty);
}

var btn = new Button();
btn.Clicked += (s, e) => Console.WriteLine("Button 1 clicked!");
btn.Clicked += (s, e) => Console.WriteLine("Button 2 clicked!");

btn.Click(); // Both handlers fire