skip to content

Func and Action Types

A delegate is a type-safe method reference; Func and Action cover most shapes, and multicast delegates call a list. Interviewers ask what a multicast delegate returns.

on this pageshow

questions

5

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

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#, 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

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