skip to content

Delegates and Events

Delegates, lambdas, closures and events: the callback model under LINQ, async and UI code. Interviewers ask about closures, multicast calls and event leaks.

on this pageshow

explore

questions

20

In C#, when do Func, Action and Predicate fit a callback, and when do you still declare your own delegate type?

level: juniorimportance: must knowfreq 70%

answer

  1. return value or void
  2. one T in, bool out
  3. by-value type arguments only
  4. out parameter on TryParse
  5. delegate types are nominal

basics

~20 s

Func<..., TResult> wraps a method that returns a value, Action<...> one that returns void, and Predicate<T> a T-to-bool test. Declare your own delegate type when a parameter is ref, out or in, or when a named type should document intent.

solid answer

~40 s

A delegate type is a type-safe reference to a method with one exact signature. The BCL's generic `Func<T1, ..., TResult>` (up to 16 parameters) covers methods that return a value, `Action<T1, ...>` covers `void` methods, and `Predicate<T>` is the older `T`-to-`bool` shape that `List<T>.FindAll` and `Array.FindAll` still take, while LINQ's `Where` takes `Func<T, bool>`. Their type parameters are passed by value, so a callback with a `ref`, `out` or `in` parameter, such as the shape of `decimal.TryParse`, needs a declared type like `delegate bool PriceParser(string text, out decimal value);`. A named type also earns its place when the name and parameter names document a domain concept. Delegate types are nominal: a `Predicate<decimal>` does not convert to `Func<decimal, bool>` even though the signatures match.

code

csharp · 18 lines
csharp
using System;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

Func<decimal, decimal> seasonal = price => price * 0.90m;   // one in, one out
Action<string> audit = message => Console.WriteLine($"audit: {message}");
Predicate<decimal> isSellable = price => price > 0m;

PriceParser parse = decimal.TryParse;   // out parameter: Func cannot express this
if (parse("40.00", out decimal listPrice) && isSellable(listPrice))
    audit($"{listPrice} -> {seasonal(listPrice)}");

// Func<decimal, bool> check = isSellable;      // CS0029: delegate types are nominal
Func<decimal, bool> check = isSellable.Invoke;  // method group conversion instead
Console.WriteLine(check(-1m));

delegate bool PriceParser(string text, out decimal value);

go deeper

for a junior

Recall the three families: Func returns a value and its last type argument is the result, Action returns void, Predicate tests one value and returns bool.

for a middle

Explain why TryParse-shaped callbacks need a declared delegate type and why Predicate<T> does not convert to Func<T, bool> without the Invoke method group.

for a senior

Choose between a named delegate type and Func in a public API: readability and parameter names against the friction of a nominal type that callers must adapt to.

for a principal

Treat delegate shapes as API surface: prefer the built-in types for interoperability and reserve named delegates for by-reference parameters or a domain concept worth naming.

## What a delegate type is A **delegate** in C# is an object that holds a reference to a method, plus the target instance when the method is an instance method. A **delegate type** fixes the signature that every referenced method must match: the parameter types, their `ref`/`out`/`in` modifiers and the return type. Calling the delegate calls the method. Every delegate type derives from `System.MulticastDelegate`, so any delegate can also hold a list of methods, which matters later for multicast calls. You can declare a delegate type yourself with the `delegate` keyword: ```csharp delegate decimal DiscountRule(decimal price); ``` Most code never needs to, because the base class library ships generic delegate types for almost every shape. ## The built-in shapes | Type | Shape | Typical consumer | |---|---|---| | `Func<TResult>` ... `Func<T1, ..., T16, TResult>` | 0-16 parameters, returns `TResult` | LINQ's `Select`, `Where`, `OrderBy` | | `Action` ... `Action<T1, ..., T16>` | 0-16 parameters, returns `void` | `List<T>.ForEach`, logging callbacks | | `Predicate<T>` | one `T`, returns `bool` | `List<T>.Find`, `FindAll`, `RemoveAll`, `Array.FindAll` | - The **last** type argument of `Func` is always the return type: `Func<decimal, decimal>` takes a price and returns a price. - `Predicate<T>` and `Func<T, bool>` have the same shape but are **different types**; which one you write is decided by the API you hand it to. - A lambda or method group converts to whichever delegate type the target expects, so `isSellable` can be written once as a lambda and passed to either API. ## When a custom delegate type earns its place 1. **A by-reference parameter.** The generic delegates take their arguments by value. A callback shaped like `decimal.TryParse(string, out decimal)` needs a declared type such as `delegate bool PriceParser(string text, out decimal value);`. The same applies to `ref` and `in` parameters. 2. **More than 16 parameters**, which no `Func` or `Action` overload covers (and which is a design smell in its own right). 3. **A name that carries meaning.** `DiscountRule` in a pricing engine reads better in signatures and IDE tooltips than `Func<decimal, decimal>`, and its parameter names show up in completion lists. 4. **A `params` parameter or attributes** on the delegate's parameters, which a closed `Func` cannot carry. For everything else, `Func` and `Action` are the idiomatic choice, and reviewers will ask why a new type was introduced. ## Delegate types are nominal Two delegate types with identical signatures are still unrelated types. Assigning a `Predicate<decimal>` to a `Func<decimal, bool>` variable fails with **CS0029** ("Cannot implicitly convert type"), and an explicit cast fails with **CS0030**. The fix is a **method group conversion**: `Func<decimal, bool> check = isSellable.Invoke;` builds a new `Func` whose target is the predicate's `Invoke` method. The same rule is why a custom `DiscountRule` will not flow into an API that expects `Func<decimal, decimal>` without that extra hop, and it is a practical argument for preferring the built-in types in public APIs. ## Common mistakes in code review - **`Func<void>`.** `void` is not a type argument; the compiler reports **CS1547** ("Keyword 'void' cannot be used in this context"). A `void` callback is an `Action`. - **Swapping `Action<T1, T2>` and `Func<T1, T2>`.** The first takes two arguments and returns nothing; the second takes one argument and returns a `T2`. - **A new delegate type per callback.** Declaring `PriceChecker`, `PriceValidator` and `PriceFilter` with the same shape creates three types that do not convert to each other, so every caller has to adapt. Use `Func<decimal, bool>` unless the name or a by-reference parameter justifies a declaration. - **Choosing `Predicate<T>` for a new API** whose callers already hold `Func<T, bool>` values from LINQ code; they will need the `.Invoke` hop on every call. ## In an interview - Name the three families and what the last type argument of `Func` means. - Say that the generic delegates cannot express `ref`, `out` or `in` parameters, and give `TryParse` as the example. - Mention that delegate types are nominal and show the `.Invoke` workaround. - Keep delegate variance (assigning `Action<object>` to `Action<string>`) out of it unless asked: that is the generics lesson's material, and it applies only within one generic delegate type, never across two different delegate types.

  • Why do List<T>.FindAll and Array.FindAll take Predicate<T> while Enumerable.Where takes Func<T, bool>?
    `Predicate<T>` is older than the generic `Func` family, and the collection methods written in its era were typed against it. LINQ, which came later, standardised on `Func<T, bool>`. Both shapes are still public API, so the types cannot be unified; a lambda converts to either one, which is why most code never notices.
  • Can a lambda with an out parameter be stored in a variable without declaring a delegate type?
    Yes, since C# 10 `var` can infer a natural type for it, but because `Func` and `Action` cannot express `out`, the compiler synthesizes an internal anonymous delegate type. That works locally; to pass the callback through a public method signature you still need a named delegate type, because the synthesized one cannot be written in source.

  • Predicate<decimal> and Func<decimal, bool> are the same type, so one assigns to the other
  • Func can take an out parameter by writing Func<string, out decimal, bool>
  • The last type argument of Func is its first parameter, not its return type
  • Action can return a value when the method being referenced returns one
  • Custom delegate types are obsolete and the compiler warns about them
open as a page

How do you declare and raise a C# event that follows the EventHandler<TEventArgs> convention, and what goes in sender and e?

level: juniorimportance: must knowfreq 65%

basics

~10 s

Declare event EventHandler<PriceChangedEventArgs>? PriceChanged, raise it from a protected virtual OnPriceChanged method with PriceChanged?.Invoke(this, e): sender is the publisher, e carries the data, and EventArgs.Empty stands in when there is none.

open as a page

In C#, how does an expression lambda differ from a statement lambda, and where does the compiler get a lambda's parameter types?

level: juniorimportance: must knowfreq 70%

basics

~20 s

An expression lambda's body is a single expression whose value is the result; a statement lambda's body is a block that must return explicitly on every path. Untyped parameters take their types from the delegate the lambda is converted to.

open as a page

In C#, when a document window subscribes to a settings service's event, which of the two objects does the subscription keep alive, and why?

level: juniorimportance: must knowfreq 70%

basics

~20 s

The publisher keeps the subscriber alive. The += operator stores a delegate in the settings service's event field, and that delegate's Target is the window or a closure that captured it, so the service reaches the window until it unsubscribes.

open as a page

In C#, three discount rules are combined into one Func<decimal, decimal> with +=; what does invoking it return?

level: middleimportance: must knowfreq 65%

basics

~20 s

Every rule runs in the order it was added, each with the caller's original argument, and the call returns only the last rule's result. Earlier return values are discarded; to use them, iterate GetInvocationList() and invoke each target yourself.

open as a page

In C#, what does declaring PriceChanged with the event keyword change compared with exposing a public delegate field of the same type?

level: middleimportance: must knowfreq 72%

basics

~10 s

The event keyword limits code outside the declaring type to += and -=. A public delegate field also lets any caller overwrite every subscriber with = or null and raise the notification itself.

open as a page

In C#, why do callbacks created in a for loop all see the counter's final value, while a foreach loop gives each its own?

level: middleimportance: must knowfreq 80%

basics

~20 s

A for loop declares its counter once, and every lambda captures that one variable, so all callbacks see its final value. Since C# 5 a foreach loop declares a fresh iteration variable per pass, so each callback keeps its own element.

open as a page

In C#, why does settings.Changed -= (s, e) => window.Refresh() fail to remove the handler that an identical lambda added with +=?

level: middleimportance: must knowfreq 65%

basics

~20 s

Each lambda expression compiles to its own method, so the lambda written after -= is a different delegate from the one added. Delegate.Remove finds no equal entry and silently leaves the list unchanged; store the delegate and remove that instance.

open as a page

In C#, why is if (PriceChanged != null) PriceChanged(this, e) unsafe when dashboards unsubscribe from other threads, and what fixes it?

level: seniorimportance: must knowfreq 60%

basics

~20 s

The check and the call read the event's backing field separately; if the last handler unsubscribes in between, the call hits null and throws NullReferenceException. PriceChanged?.Invoke(this, e) reads the field once and invokes that immutable delegate.

open as a page

A C# desktop app's memory grows with every document window closed, and each window subscribed to a long-lived settings service's Changed event; why, and how do you fix it?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Each closed window is still reachable: the settings service's Changed field holds a delegate whose Target is the window. Fix it by unsubscribing with an equal delegate when the window closes, typically in Dispose, and making sure Dispose is called.

open as a page

In C#, a pricing engine copies its rules delegate into a local, then adds a rule with +=; why doesn't the copy run it?

level: middleimportance: should knowfreq 45%

basics

~20 s

Delegates are immutable: += compiles to Delegate.Combine, which builds a new delegate with a longer invocation list and assigns it to the variable. The copy still references the old instance, so it keeps the old list.

open as a page

When would you write custom add and remove accessors for a C# event, and what changes inside the class once you do?

level: middleimportance: should knowfreq 35%

basics

~20 s

Write add and remove bodies when subscriptions need custom storage, forwarding, locking or bookkeeping. Then no backing field exists, so the class raises its own stored delegate, because using the event name for anything but += or -= is error CS0079.

open as a page

In C#, what does the compiler generate when a lambda captures a local variable, and why do two lambdas capturing it see each other's writes?

level: middleimportance: should knowfreq 60%

basics

~20 s

The compiler moves a captured local into a field of a generated closure class, one instance per scope entry. The method and every lambda in that scope use that one field, so any write is seen by all.

open as a page

In C#, one check in a multicast Action<string> validation delegate throws; which checks ran, and how do you make every check run?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Targets before the failing one have run, the failing one throws, and the targets after it never run; the original exception reaches the caller unwrapped. To run every check, invoke each GetInvocationList() entry in its own try/catch and collect the failures.

open as a page

Since C# 10, var floor = Pricing.ApplyFloor; compiles for a single-overload method; what delegate type is inferred, and when does inference fail?

level: seniorimportance: should knowfreq 35%

basics

~20 s

C# 10 gives a lambda or method group a natural type: Func<...> when it returns a value, Action<...> when void, or a synthesized type when neither fits the signature. It fails with CS8917 when overloads share no signature or lambda parameters are untyped.

open as a page

In C#, are += and -= on a field-like event thread-safe, and what does the compiler generate for its add and remove accessors?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Yes. The compiler-generated add and remove accessors build a new delegate with Delegate.Combine or Delegate.Remove and publish it with Interlocked.CompareExchange in a retry loop, so concurrent subscriptions are not lost. Hand-written accessors get none of that.

open as a page

A C# order filter on a hot path calls orders.Exists(o => o > threshold) on every request; what does each call allocate, and how do static lambdas help?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Capturing threshold costs a closure object and a new delegate on every call; a non-capturing lambda's delegate is cached and reused. A static lambda (C# 9) makes any accidental capture a compile error, so state must be passed as an argument.

open as a page

In C#, why does a weak event that stores each handler as a WeakReference<EventHandler> stop firing almost at once, and what should it hold weakly instead?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Only the WeakReference points at the delegate object, so the next collection frees it while the subscriber lives on. A weak event must hold the subscriber, the delegate's Target, weakly and keep the method strongly, then prune dead entries.

open as a page

As lead of a large C# desktop codebase, what rule would you set for event subscriptions from short-lived views to long-lived services, and why?

level: principalimportance: should knowfreq 30%

basics

~20 s

Make subscription ownership explicit: long-lived services return an IDisposable subscription that the view disposes with its own lifetime, static events are banned for view code, and weak events are kept for publishers that cannot know their subscribers.

open as a page

What did C# 12 and C# 14 change about C# lambda parameters, such as default values, params and writing out without a type?

level: middleimportance: nice to knowfreq 25%

basics

~20 s

C# 12 lets explicitly typed lambda parameters have default values and params arrays. C# 14 lets implicitly typed parameters carry ref, out, in, ref readonly or scoped without writing the type; params still needs a type, and defaults still need explicit types.

open as a page