Glossary / Delegates

Delegates

A delegate is a type-safe reference to one or more callable methods with a defined parameter and return signature. Delegates enable callbacks, event handlers, and higher-order APIs; they preserve compile-time signature checks while allowing behavior to be passed as data.

Invocation and composition

Func<int, int> square = x => x * x;
Console.WriteLine(square(4)); // 16

A delegate instance can reference static or instance methods and closures. Multicast delegates combine invocation lists with +=; invocation calls handlers in order. For non-void delegates, the return value is from the last invoked method. If a handler throws, normal invocation stops unless each callback is isolated manually. Delegate equality compares invocation lists under defined rules.

Built-in generic delegates include Action (void result), Func (result), and Predicate<T>. Captured lambdas can allocate closure objects and retain captured state beyond the creating method's apparent lifetime. Delegates are immutable objects; combining/removing creates new delegate values.

Engineering guidance

Use delegates for behavior parameters and small callback contracts. Prefer named interfaces when the interaction has multiple operations, state, cancellation, or complex lifecycle. Avoid retaining callbacks longer than intended, especially event handlers. Document multicast exception and ordering behavior if accepting multicast delegates.

Interview questions

  1. What does a delegate represent? A type-safe callable reference matching a signature.
  2. What is multicast behavior? A delegate can hold multiple methods invoked in order.
  3. Which return value is returned? For a non-void multicast delegate, the final invocation's result.
  4. What does a captured lambda retain? Captured variables/state, potentially extending their lifetime.
  5. Delegate vs interface? Delegate models a callable operation; interface models a broader object capability/contract.

References