Delegates
Learn how delegates let you treat methods as values that can be passed around and invoked dynamically.
What is a Delegate?
A delegate is a type-safe reference to a method — it lets you treat a method like a value: store it in a variable, pass it as a parameter, or return it from another method.
Declaring and Using a Delegate
delegate int MathOperation(int a, int b);
static int Add(int a, int b) => a + b;static int Multiply(int a, int b) => a * b;
MathOperation operation = Add;Console.WriteLine(operation(3, 4)); // 7
operation = Multiply;Console.WriteLine(operation(3, 4)); // 12Output
Click Run to see what this code prints.
Built-in Delegate Types
Rather than declaring a custom delegate every time, C# provides built-in generic delegate types for common cases.
| Type | Purpose |
|---|---|
| Action | A method with no return value |
| Action<T> | A method with parameters and no return value |
| Func<T, TResult> | A method that takes T and returns TResult |
| Predicate<T> | A method that takes T and returns bool |
Func<int, int, int> add = (a, b) => a + b;Console.WriteLine(add(5, 3));
Action<string> log = message => Console.WriteLine($"LOG: {message}");log("Application started");Output
Click Run to see what this code prints.
FAQs
Delegates power events (next lesson), LINQ, and any API that lets you "plug in" custom logic — like sorting with a custom comparison.
Summary
- A delegate is a type-safe reference to a method.
- Func, Action, and Predicate are built-in generic delegate types.
- Delegates are the foundation events and LINQ are built on.