Module 1 · Expression Trees, Delegates and Generics · Lesson 2 of 8
Delegates, Func/Action and custom delegates
The same variable calls Add, then Multiply. Later, a notification list stops at a throwing handler. Which parts are selected behavior, and which parts are guaranteed invocation order?
The small snippets are independent examples using System; do not concatenate their top-level statements after type declarations.
// Methods that match the signature static int Add(int a, int b) => a + b; static int Multiply(int a, int b) => a * b; // Assign methods to the delegate PerformCalculation calc = Add; Console.WriteLine(calc(3, 4)); // 7 calc = Multiply; Console.WriteLine(calc(3, 4)); // 12 // Declare a delegate type that takes two ints and returns an int public delegate int PerformCalculation(int x, int y);
Select a callback type
A delegate is a typed invocation list, with a target object for an instance method where needed. Compatible static or instance methods can be assigned through a method group. Func's final argument is its result type; Action returns void. Predicate<T> has the same call shape as Func<T, bool> but remains a different named delegate type.
Func<int, int, int> add = (a, b) => a + b; Action<string> logger = message => Console.WriteLine(message); Predicate<int> isEven = n => n % 2 == 0;
Use a custom delegate for a useful domain name or a signature requiring ref/out parameters. It can declare its own type parameters:
static void Notify(int i) { /*...*/ }
Del<int> m1 = new Del<int>(Notify); // explicit assignment
Del<int> m2 = Notify; // method group conversion
public delegate void Del<T>(T item);Which delegate type?
- Func<..., TResult>
- Takes inputs and returns a value Func<int, int, int> add
- Action<...>
- Takes inputs and returns void Action<string> log
- Custom delegate
- When a named type conveys intent better Transformer<T, TResult>
- Multicast
- += chains handlers; only the last return value is kept notify += SendSms
Follow three uses
For CountMatches, assume non-null equal-length arrays and a non-null predicate. Predict the equality count and greater-than count before running the fragment.
static int CountMatches(int[] xs, int[] ys, Func<int, int, bool> predicate)
{
int count = 0;
for (int i = 0; i < xs.Length; i++)
{
if (predicate(xs[i], ys[i]))
count++;
}
return count;
}
// Use the method with different delegates
int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 2, 1, 4 };
int equalCount = CountMatches(a, b, (x, y) => x == y);
int greaterCount = CountMatches(a, b, (x, y) => x > y);
Console.WriteLine($"Equal: {equalCount}, Greater: {greaterCount}");Check: the algorithm owns traversal; the callback owns the pairwise decision. Changing a predicate does not require rewriting the loop.
Next predict which handler prints first. The two handlers below return void.
// Define two handlers
static void SendEmail(string msg) => Console.WriteLine($"Email: {msg}");
static void SendSms(string msg) => Console.WriteLine($"SMS: {msg}");
Notification notify = SendEmail;
notify += SendSms;
notify("Your order has shipped");
// Output:
// Email: Your order has shipped
// SMS: Your order has shipped
public delegate void Notification(string message);The next custom generic delegate gives transformation a name. Compare its parameter/result types with Func before running it.
// Use it to transform strings to numbers
static int LengthOfString(string s) => s.Length;
Transformer<string, int> getLength = LengthOfString;
Console.WriteLine(getLength("hello")); // 5
public delegate TResult Transformer<T, TResult>(T input);Predict the complete experiment
Copy the following whole Program.cs into a .NET 10 console project with nullable reference types enabled. Use these questions as the reading map:
| Case | Predict before running |
|---|---|
| Double followed by AddTen | Which return value reaches the caller? |
| Email, throwing SMS, then Push | Does Push run? |
| Repeated Log and one removal | Which matching registration is removed? |
| Shared counter versus per-iteration copy | Why do the captured results differ? |
| PriceRule with out | Why is a custom delegate useful? |
using System;
using System.Collections.Generic;
public static class Program
{
public static void Main()
{
// 1. Multicast with return values: every handler runs, only the last result is returned.
Func<int, int> pipeline = Double;
pipeline += AddTen;
Console.WriteLine($"multicast result: {pipeline(5)}");
foreach (Func<int, int> step in pipeline.GetInvocationList())
Console.WriteLine($" {step.Method.Name}(5) = {step(5)}");
// 2. An exception in one handler stops the handlers after it.
Action<string> notify = msg => Console.WriteLine($"Email: {msg}");
notify += msg => throw new InvalidOperationException("SMS gateway down");
notify += msg => Console.WriteLine($"Push: {msg}");
try
{
notify("Order shipped");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"stopped: {ex.Message}");
}
// 3. -= needs an equal delegate; do not rely on a newly written lambda matching an earlier handler.
Action<string>? log = Log;
log += Log;
log -= Log;
Console.WriteLine($"after -= Log: {log?.GetInvocationList().Length ?? 0} handler(s)");
Action<string>? lambdas = s => Console.WriteLine(s);
lambdas -= s => Console.WriteLine(s);
Console.WriteLine($"after -= new lambda: {lambdas?.GetInvocationList().Length ?? 0} handler(s)");
// 4. Variance.
Func<string> makeText = () => "covariant";
Func<object> makeObject = makeText; // string -> object return: covariance
Action<object> printAny = o => Console.WriteLine($"contravariant got {o}");
Action<string> printText = printAny; // object parameter accepts string: contravariance
printText((string)makeObject());
// 5. Closures capture variables, not values.
var actions = new List<Func<int>>();
int counter = 0;
for (int i = 0; i < 3; i++)
{
counter++;
actions.Add(() => counter);
}
counter = 100;
Console.WriteLine($"captured variable: {string.Join(",", actions.ConvertAll(a => a()))}");
var copies = new List<Func<int>>();
for (int i = 0; i < 3; i++)
{
int copy = i;
copies.Add(() => copy);
}
Console.WriteLine($"per-iteration copy: {string.Join(",", copies.ConvertAll(a => a()))}");
// 6. A named custom delegate documents intent where Func would not.
PriceRule discount = (decimal price, out string reason) =>
{
reason = price > 100m ? "10% over 100" : "none";
return price > 100m ? price * 0.9m : price;
};
decimal final = discount(250m, out string why);
Console.WriteLine($"price rule: {final} ({why})");
}
static int Double(int x) => x * 2;
static int AddTen(int x) => x + 10;
static void Log(string s) => Console.WriteLine(s);
}
public delegate decimal PriceRule(decimal price, out string reason);Recorded illustrative output follows. The line involving a newly written lambda is implementation-dependent; the decimal output also assumes a decimal-point culture.
multicast result: 15 Double(5) = 10 AddTen(5) = 15 Email: Order shipped stopped: SMS gateway down after -= Log: 1 handler(s) after -= new lambda: 1 handler(s) contravariant got covariant captured variable: 100,100,100 per-iteration copy: 0,1,2 price rule: 225.0 (10% over 100)
Quick check
In the complete program, the SMS handler throws before the Push handler. What follows?
Show answer
Correct answer: C
An ordinary multicast invocation stops at an uncaught handler exception. It supplies neither retries nor rollback.
Option A: Later entries are skipped after the exception.
Option B: Retry is an application policy, not a delegate operation.
Option D: Earlier ordinary side effects are not automatically undone.
Contract reference: Microsoft documentation.
Check the guarantee, not an accidental identity
Ordinary multicast calls run synchronously in invocation-list order. Only the last completed handler's return value reaches the caller. An uncaught handler exception stops later entries. If every result or every handler must be processed, explicitly iterate GetInvocationList and define per-entry error handling.
Delegates are immutable. Combining/removing assigns a resulting value; code holding an old value still holds its old invocation list. Removal takes the last matching occurrence/subsequence. Single-entry equality requires the same delegate runtime type, method and target where applicable. A newly written similar lambda is not a reliable way to remove an earlier one; retain the original delegate.
Return covariance and input contravariance allow the demonstrated reference-type substitutions. They do not box Func<int> into Func<object>. Two distinct named delegate types do not become identical because their signatures match.
Try: make capture and removal explicit
Before changing the program, predict which lambdas read the shared counter after it becomes 100. Hint: lambdas capture variables, not a snapshot of their values; the copy inside each iteration is a different variable. Check: shared captures read 100 while copies produce 0, 1 and 2.
For reliable removal, keep and remove the original handler reference. Check the remaining invocation count rather than requiring the illustrated new-lambda result to be 1 on every compiler. Captures can retain objects for as long as reachable delegates need them; exact allocation counts and mutable-target thread safety require separate evidence.
TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·