1.11 — Delegates, Func, Action, Predicate¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.10 Generics · Next: 1.12 Events
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- A delegate is a variable that holds a method. You can pass it around and call it later.
- You almost never need to declare your own any more. Use the built-in ones:
Action(returns nothing),Func(returns something),Predicate(returnsbool). - A delegate can hold more than one method at once. That is called multicast, and it is how events work.
The concept¶
Normally a variable holds data — a number, a string, an object. A delegate holds a method.
Why is that useful? Because it lets you pass behaviour into a method, not just data.
A real-world picture: think of giving someone a phone number instead of an answer. You are not saying "the answer is 42". You are saying "when you need the answer, call this number". Whoever holds the number can call it whenever they like, and they do not need to know who picks up.
This is what makes LINQ, event handlers, and callbacks possible.
How it works¶
The old way — declaring your own¶
// This declares a TYPE. It says: "a method that takes two ints
// and returns an int".
public delegate int MathOperation(int a, int b);
// Any method matching that shape can be stored in it
static int Add(int a, int b) => a + b;
static int Multiply(int a, int b) => a * b;
MathOperation op = Add;
int result = op(3, 4); // 7 — this actually calls Add
op = Multiply;
result = op(3, 4); // 12 — same variable, different method
Notice op = Add has no brackets. You are storing the method itself, not calling it.
Adding brackets would call it and store the result instead.
The modern way — built-in delegate types¶
You rarely declare your own delegate now. .NET provides generic ones that cover almost every shape:
| Type | Shape | Example |
|---|---|---|
Action |
takes nothing, returns nothing | Action greet = () => Console.WriteLine("hi"); |
Action<T> |
takes a T, returns nothing | Action<string> log = m => Console.WriteLine(m); |
Action<T1,T2> |
takes two, returns nothing | up to 16 parameters |
Func<TResult> |
takes nothing, returns a value | Func<int> get = () => 42; |
Func<T,TResult> |
takes a T, returns a value | Func<int,int> dbl = x => x * 2; |
Predicate<T> |
takes a T, returns bool | Predicate<int> isEven = x => x % 2 == 0; |
The rule for Func: the last type parameter is always the return type. So
Func<int, string, bool> takes an int and a string, and returns a bool.
Predicate<T> is really just Func<T, bool> with a friendlier name. LINQ actually uses
Func<T, bool>, not Predicate<T>.
So the earlier example becomes:
Multicast — holding several methods¶
A delegate can hold a whole list of methods. Use += to add and -= to remove:
Action<string> pipeline = m => Console.WriteLine($"Console: {m}");
pipeline += m => File.AppendAllText("log.txt", m);
pipeline += m => telemetry.Track(m);
pipeline("Order created");
// Calls ALL THREE, in the order they were added.
Two things to be careful about with multicast delegates:
Only the last return value survives. If you multicast a Func, you get the result of
the final method and every other result is silently thrown away. So multicasting only
really makes sense for Action.
One exception stops everything after it. If the second method throws, the third never runs. If you need all of them to run regardless, you have to invoke them individually:
foreach (Action<string> handler in pipeline.GetInvocationList())
{
try { handler(message); }
catch (Exception ex) { logger.LogError(ex, "Handler failed"); }
}
Where you already use delegates without noticing¶
Every LINQ method takes a delegate:
orders.Where(o => o.Total > 100) // Func<Order, bool>
.Select(o => o.CustomerName) // Func<Order, string>
.OrderBy(name => name) // Func<string, string>
Each of those lambdas is a delegate being passed in. Where does not know what "expensive
order" means — you tell it, by handing it a method.
Code¶
Here is a realistic use: a retry helper that works with any operation.
public static async Task<T> RetryAsync<T>(
Func<CancellationToken, Task<T>> operation, // the work to do
int maxAttempts,
ILogger logger,
CancellationToken ct)
{
for (var attempt = 1; ; attempt++)
{
try
{
return await operation(ct); // call whatever we were given
}
catch (Exception ex) when (attempt < maxAttempts)
{
logger.LogWarning(ex, "Attempt {Attempt} failed, retrying", attempt);
await Task.Delay(TimeSpan.FromSeconds(attempt), ct);
}
}
}
Used like this:
var order = await RetryAsync(
ct => httpClient.GetFromJsonAsync<Order>("/orders/1", ct),
maxAttempts: 3,
logger,
cancellationToken);
RetryAsync has no idea what it is retrying. It could be an HTTP call, a database query,
or a file read. The delegate parameter is what makes it reusable — without it you would
need a separate retry method for every kind of operation.
(In a real ASP.NET Core app you would use Polly for this rather than hand-rolling it — see 19.11. But the pattern is the same.)
Interview questions¶
Q: What is a delegate?
It is a type that holds a reference to a method, so you can store a method in a variable, pass it as an argument, and call it later. It is type-safe — the delegate's declaration specifies the parameters and return type, and the compiler checks that whatever you assign matches. Delegates are what make callbacks, event handlers, and LINQ possible, because they let you pass behaviour into a method rather than just data.
Q: What is the difference between Action, Func and Predicate?
They are all built-in generic delegate types. Action returns nothing — it is for methods
you call for their side effects. Func returns a value, and the last type parameter is
always the return type, so Func<int, string> takes an int and returns a string.
Predicate<T> takes a T and returns a bool, so it is for tests and filters. In practice
Predicate<T> is just a friendlier name for Func<T, bool>, and LINQ actually uses the
Func form.
Q: What is a multicast delegate?
A delegate that holds more than one method. You add methods with += and remove them with
-=, and invoking the delegate calls all of them in the order they were added. It is the
mechanism behind events. Two things to watch: if the delegate returns a value you only get
the last one, and if any handler throws, the ones after it never run. If you need every
handler to run independently, you have to loop over GetInvocationList() and call them
one at a time inside a try/catch.
Q: What is the difference between a delegate and an interface with one method?
They solve the same problem in different ways. An interface is better when the thing has
identity and might grow more members, or when you want to inject it and mock it. A delegate
is better for a single, simple, throwaway piece of behaviour — especially when you want to
write it inline as a lambda. LINQ uses delegates because writing
Where(o => o.Total > 100) inline is far nicer than declaring a class that implements
IFilter<Order> every time.
Traps ⚠️¶
op = Addversusop = Add(). No brackets stores the method. Brackets calls it and stores the result. Easy typo, confusing error.- Multicast
Functhrows away all but the last return value, silently. - One throwing handler stops the rest. Use
GetInvocationList()if that matters. -=needs the exact same delegate instance to remove a lambda. Subscribing withx += () => Foo()and then unsubscribing withx -= () => Foo()does nothing at all — they are two different lambda objects. Store it in a variable first.- A delegate holding an instance method keeps that whole object alive. This is the main cause of event-related memory leaks — see 1.12.
Func<T,bool>andPredicate<T>are not interchangeable even though they look identical. They are different types, so you cannot pass one where the other is expected without conversion.
Related¶
- 1.12 Events — delegates with restricted access
- 1.13 Lambdas and closures — the usual way to write a delegate
- 2.5 LINQ — delegates everywhere
- 2.7 Expression trees — when a delegate becomes data instead
- 22.5 Strategy pattern — a delegate is often a lightweight strategy