Lesson 20 of 30
Delegates and Events
C# in Visual Studio 2026 — a hands-on guide for developers at every level.
Delegates
A delegate is a type-safe function pointer. It can hold a reference to any method with a matching signature.
// Declare delegate type
delegate int MathOp(int a, int b);
static int Add(int a, int b) => a + b;
static int Multiply(int a, int b) => a * b;
MathOp op = Add;
Console.WriteLine(op(3, 4)); // 7
op = Multiply;
Console.WriteLine(op(3, 4)); // 12
Func and Action
Instead of declaring custom delegate types, use the built-in Func and Action:
Func<int, int, int> add = (a, b) => a + b;
Action<string> print = msg => Console.WriteLine(msg);
print(add(10, 20).ToString()); // 30
Events
An event is a delegate that can only be invoked from the class that declares it. This is the Observer pattern built into the language.
public class Button
{
public event EventHandler? Clicked;
public void Click() => Clicked?.Invoke(this, EventArgs.Empty);
}
var btn = new Button();
btn.Clicked += (sender, e) => Console.WriteLine("Button clicked!");
btn.Click();
Multicast Delegates
Action actions = () => Console.WriteLine("First");
actions += () => Console.WriteLine("Second");
actions += () => Console.WriteLine("Third");
actions(); // First, Second, Third