CKTIS / C#
System.Predicate<T> — a delegate for testing a condition
System.Predicate<T> describes a test that takes one argument of type T and returns bool. It lets you store a condition in a variable, invoke it directly, or pass it to a search method such as Array.Find.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
Predicate<int> predicate = obj => obj % 2 == 0;
int value = 8;
bool matches = predicate(value);System.Predicate<T> is a generic delegate type representing a test of one argument of type T. A result of true means the condition is satisfied; false means it is not. The delegate holds a reference to an executable test, not the result of testing.
You can assign a lambda expression or a compatible method returning bool to it. In the example, Predicate<int> isEven = number => number % 2 == 0; defines an even-number test. Calling isEven(3) executes the test and returns false.
Array.Find(numbers, isEven) checks elements in order and returns the first matching element, here 8, rather than a Boolean value. If nothing matches, it returns default(T); for int, that is 0, so the result alone does not always identify a missing match.
Examples
using System;
internal static class Program
{
private static void Main()
{
Predicate<int> isEven = number => number % 2 == 0;
int[] numbers = { 3, 7, 8, 10 };
Console.WriteLine(isEven(3));
Console.WriteLine(Array.Find(numbers, isEven));
}
}Result
False 8
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.