Delegates, lambdas and events
A delegate lets you pass a method around like a value, a lambda is its short inline form, and an event is a protected delegate for the publisher/subscriber pattern. Together they remove copy paste code, but closures and forgotten unsubscribes cause classic bugs.
22.1 Why is it used?
- Often the loop stays the same and only the behaviour (the condition in the middle) changes.
- Copying the whole method per rule means one loop bug must be fixed in every copy.
- A delegate makes the behaviour itself a parameter: write the loop once, pass the rule.
- Events let a class announce something (order placed) without knowing who listens (SMS, email).
22.2 The problem: a new copy for every rule
int[] amounts = [250, 1200, 799, 4500];Console.WriteLine(Big(amounts));Console.WriteLine(Small(amounts)); static string Big(int[] items){ List<int> result = []; foreach (var x in items) if (x > 1000) result.Add(x); return string.Join(", ", result);} // Small(): copy of Big, only the// condition changes to x < 500$ dotnet run Copy.cs1200, 450025022.3 Fix: a Func<int, bool> parameter
- A delegate is a type that holds a reference to a method; Func<int, bool> takes an int and returns a bool.
- rule(x) runs whichever method was passed in.
- Pass a method name without brackets (IsBig) or a lambda directly (x => x < 500).
int[] amounts = [250, 1200, 799, 4500];Console.WriteLine(Filter(amounts, IsBig));Console.WriteLine(Filter(amounts, x => x < 500)); static bool IsBig(int x) => x > 1000; static string Filter(int[] items, Func<int, bool> rule){ List<int> result = []; foreach (var x in items) if (rule(x)) result.Add(x); return string.Join(", ", result);}$ dotnet run Filter.cs1200, 450025022.4 Func, Action, Predicate
| Delegate | Returns | Example |
|---|---|---|
| Func<T1, ..., TResult> | The last type argument (TResult) | Func<int, int, int> add = (a, b) => a + b; |
| Action<T1, ...> | Nothing (void) | Action<string> log = msg => Console.WriteLine(msg); |
| Predicate<T> | Always bool | Predicate<int> isEven = n => n % 2 == 0; |
Func<int, int, int> add = (a, b) => a + b;Action<string> log = msg => Console.WriteLine($"[log] {msg}");Predicate<int> isEven = n => n % 2 == 0; Console.WriteLine(add(499, 99));log("Order placed");Console.WriteLine(isEven(7)); Func<decimal, decimal> withGst = price =>{ var gst = price * 0.18m; return price + gst;};Console.WriteLine(withGst(1000m));$ dotnet run Types.cs598[log] Order placedFalse1180.00- Expression lambda: x => x * 2 (one expression, result returned automatically).
- Statement lambda: price => { ...; return ...; } for several lines.
22.5 Closures and the loop bug
- A lambda can capture a local variable; it lives on even after the method ends.
- Each call of next() increases the same captured count.
var next = MakeCounter();Console.WriteLine(next());Console.WriteLine(next());Console.WriteLine(next()); static Func<int> MakeCounter(){ int count = 0; return () => ++count;}$ dotnet run Counter.cs123Checkpoint: a lambda captures the variable, not its value, and a for loop has only one i.
List<Action> jobs = [];for (int i = 0; i < 3; i++) jobs.Add(() => Console.Write(i + " ")); foreach (var job in jobs) job();$ dotnet run Loop.cs3 3 3List<Action> jobs = [];for (int i = 0; i < 3; i++){ int copy = i; jobs.Add(() => Console.Write(copy + " "));} // Output: 0 1 2- int copy = i is a fresh variable in every iteration, so each lambda has its own value.
- foreach does not have this problem: every iteration already gets its own variable.
22.6 Events: one publisher, many subscribers
var shop = new Shop();shop.OrderPlaced += id => Console.WriteLine($"SMS sent for {id}");shop.OrderPlaced += id => Console.WriteLine($"Email sent for {id}");shop.Place("ORD-101"); class Shop{ public event Action<string>? OrderPlaced; public void Place(string id) => OrderPlaced?.Invoke(id);}$ dotnet run Shop.csSMS sent for ORD-101Email sent for ORD-101- Subscribers attach with +=; Invoke calls every handler in order.
- With no subscribers the event is null, hence OrderPlaced?.Invoke.
- The event keyword blocks outside code from assigning (= null) or firing the event: error CS0070. Only += and -= are allowed outside.
$ dotnet run Guard.csGuard.cs(3,6): error CS0070: The event 'Shop.OrderPlaced' can only appear on the left hand side of += or -= (except when used from within the type 'Shop')Guard.cs(4,6): error CS0070: ...The build failed. Fix the build errors and run again.- Step 1
1.Publisher (Shop) declares event Action<string>? OrderPlaced
- Step 2
2.Subscribers attach handlers with +=
- Step 3
3.Publisher calls OrderPlaced?.Invoke(id)
- Step 4
4.Every handler runs in order (SMS, then email)
- Step 5
5.Subscriber is done: -= unsubscribe
Every += needs a -=
22.7 The leak: screen closed, still updating
var shop = new Shop();var screen = new OrderScreen(shop);screen.Open();shop.Place("ORD-1");screen = null; // screen closedshop.Place("ORD-2"); class OrderScreen(Shop shop){ public void Open() => shop.OrderPlaced += Refresh; void Refresh(string id) => Console.WriteLine($"Screen: {id}");}$ dotnet run Leak.csScreen: ORD-1Screen: ORD-2- The shop's event still holds Refresh, and with it the screen object.
- So the GC cannot collect the screen: a memory leak, and it keeps reacting to events.
var shop = new Shop();var screen = new OrderScreen(shop);screen.Open();shop.Place("ORD-1");screen.Dispose(); // screen closedshop.Place("ORD-2");class OrderScreen(Shop shop) : IDisposable{ public void Open() => shop.OrderPlaced += Refresh; public void Dispose() => shop.OrderPlaced -= Refresh; void Refresh(string id) => Console.WriteLine($"Screen: {id}");}$ dotnet run Unsub.csScreen: ORD-1- Step 1
1.screen.Open(): shop.OrderPlaced += Refresh
- Step 2
2.Long-lived shop's event now references the screen
- Step 3
3.screen = null: our variable is gone, but the event still points to it
- Step 4
4.GC sees the screen as reachable, cannot free it
- Step 5
5.Fix: Dispose() does shop.OrderPlaced -= Refresh
The publisher keeps its subscribers alive
22.8 Comparison: delegate vs event
| Point | Public delegate field | Event |
|---|---|---|
| Outside code can +=, -= | Yes | Yes |
| Outside code can assign (= null) | Yes, wipes every handler | No, CS0070 |
| Outside code can invoke | Yes, can fire fake orders | No, only the owner class |
| Use for | Passing behaviour (callbacks, filters) | Notifications to many subscribers |
22.9 Common mistakes
- Creating lambdas in a for loop that capture the loop variable: all of them see the last value.
- Exposing a public delegate field instead of an event.
- Subscribing without ever unsubscribing, especially to a long-lived publisher.
- Myth: the GC will remove handlers automatically. As long as the publisher lives, its event keeps the subscriber alive.
22.10 Rules
- Use Func, Action and Predicate before creating your own delegate types.
- In loops, check what the lambda captures; make a local copy when needed.
- Use the event keyword, not a public delegate field.
- For every += plan a -= (Dispose is a good place).
22.11 Interview tips
- Delegate: a type safe reference to a method that can be stored, passed and called; a lambda is its short inline form.
- Func returns a value, Action returns nothing, Predicate returns bool.
- Event: a wrapper over a delegate; outside code can only += / -=, only the owner can fire it.
- Closures capture variables, not values: explain the for loop 3 3 3 bug and the local copy fix.
- Always unsubscribe: the publisher's event keeps the subscriber in memory (event handler leak).