SkillPilotAI

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

C#
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
Output
$ dotnet run Copy.cs1200, 4500250

22.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).
C#
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);}
Output
$ dotnet run Filter.cs1200, 4500250

22.4 Func, Action, Predicate

DelegateReturnsExample
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 boolPredicate<int> isEven = n => n % 2 == 0;
C#
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));
Output
$ 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.
C#
var next = MakeCounter();Console.WriteLine(next());Console.WriteLine(next());Console.WriteLine(next()); static Func<int> MakeCounter(){    int count = 0;    return () => ++count;}
Output
$ dotnet run Counter.cs123

Checkpoint: a lambda captures the variable, not its value, and a for loop has only one i.

C#
List<Action> jobs = [];for (int i = 0; i < 3; i++)    jobs.Add(() => Console.Write(i + " ")); foreach (var job in jobs) job();
Output
$ dotnet run Loop.cs3 3 3
C#
List<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

C#
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);}
Output
$ 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.
Output
$ 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.
How events work
  1. 1.Publisher (Shop) declares event Action<string>? OrderPlaced

  2. 2.Subscribers attach handlers with +=

  3. 3.Publisher calls OrderPlaced?.Invoke(id)

  4. 4.Every handler runs in order (SMS, then email)

  5. 5.Subscriber is done: -= unsubscribe

Every += needs a -=

22.7 The leak: screen closed, still updating

C#
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}");}
Output
$ 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.
C#
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}");}
Output
$ dotnet run Unsub.csScreen: ORD-1
Why a forgotten -= leaks
  1. 1.screen.Open(): shop.OrderPlaced += Refresh

  2. 2.Long-lived shop's event now references the screen

  3. 3.screen = null: our variable is gone, but the event still points to it

  4. 4.GC sees the screen as reachable, cannot free it

  5. 5.Fix: Dispose() does shop.OrderPlaced -= Refresh

The publisher keeps its subscribers alive

22.8 Comparison: delegate vs event

PointPublic delegate fieldEvent
Outside code can +=, -=YesYes
Outside code can assign (= null)Yes, wipes every handlerNo, CS0070
Outside code can invokeYes, can fire fake ordersNo, only the owner class
Use forPassing 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

  1. Use Func, Action and Predicate before creating your own delegate types.
  2. In loops, check what the lambda captures; make a local copy when needed.
  3. Use the event keyword, not a public delegate field.
  4. 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).