delegate, Action/Func, closures
Pass behavior via delegates: declare custom delegates, use built-in Action/Func, and see how lambdas capture variables (closures).
Delegates overview
Goal: Treat methods as data.
- Define a delegate type
- Use Action/Func
- Create lambdas
- Understand closures (captured variables)
Custom delegate basics
A delegate is a type-safe function pointer. Assign compatible methods and invoke like a function.
using System;
// Custom delegate type: a method taking two ints and returning int
public delegate int Op(int x, int y);
public class Program
{
static int Add(int a, int b) { return a + b; }
static int Mul(int a, int b) { return a * b; }
public static void Main(string[] args)
{
Op f = Add; // method group conversion
Console.WriteLine(f(2, 3)); // 5
f = Mul;
Console.WriteLine(f(2, 3)); // 6
}
}
All lessons in this course
- delegate, Action/Func, closures
- Events: publish/subscribe, event keyword
- Event patterns, pitfalls (memory leaks)