Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Action<T>, Func<T,TResult>, and Predicate<T> delegates

Store behavior in variables and pass it as arguments: Action performs an operation, Func returns a result, and Predicate tests a condition.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

public delegate void Action<in T>(T obj);
public delegate TResult Func<in T, out TResult>(T arg);
public delegate bool Predicate<in T>(T obj);

In C# 12 and .NET 8, these are predefined generic delegate types in the System namespace. The syntax shows the existing library declarations; don't redeclare them. Choose the type that matches what the calling code needs.

Action<T> accepts one argument of type T and returns no value (void), as when printing text. Func<T,TResult> accepts one argument of type T and returns TResult; the last type parameter is the result type. Predicate<T> accepts one argument of type T and returns bool: true if the item meets the condition, otherwise false.

Assign a compatible lambda (=>) or method group such as Console.WriteLine without parentheses to a delegate variable. The target type Action<string> helps the compiler select the overload that takes a string. Assigning or passing a delegate doesn't run its code; invoking it, as in format(word), does.

Predicate<T> and Func<T,bool> have the same call signature but are distinct types. List<T>.FindAll expects a Predicate<T> and returns a new list immediately. Enumerable.Where expects a Func<T,bool> or, in its indexed overload, a Func<T,int,bool>; it filters when enumerated. You can't pass an existing Predicate<T> variable directly to Where; wrap it with a lambda such as item => matches(item).

In these declarations, in T makes the input contravariant and out TResult makes the result covariant. These variance conversions apply to reference types, not int. A static lambda can't capture anything; a variable captured by a non-static lambda can outlive its block. Directly invoking a null delegate throws NullReferenceException; FindAll rejects a null predicate with ArgumentNullException.

Examples

using System;
using System.Collections.Generic;

List<string> words = new() { "a", "pear", "kiwi" };
Predicate<string> matches = static word => word.Length >= 4;
Func<string, string> format = static word => $"item: {word}";
Action<string> report = Console.WriteLine;

ReportMatches(words, matches, format, report);

static void ReportMatches(
    List<string> words,
    Predicate<string> matches,
    Func<string, string> format,
    Action<string> report)
{
    foreach (string word in words.FindAll(matches))
    {
        report(format(word));
    }
}

Result

item: pear
item: kiwi

`ReportMatches` receives three delegates. `FindAll` invokes `matches` for each word and keeps `pear` and `kiwi`. Then `format` adds the `item: ` prefix, and `report` prints one line per word.

Related lessons

  • C# · Lesson 21 · Intermediate · Version: 2

Sources