C# Predicate (Lambda That Returns True or False)Use the Predicate type, which is a function type that always returns a bool value to mean true or false.
dot net perls
A Predicate returns true or false. This C# type stores a method that receives 1 parameter and returns 1 value of true or false.
This type is often used with lambda expression syntax. We can create a predicate by specifying a lambda expression and passing it to a method.
We look at a program that uses 2 Predicate instances with the parameterized type of integer. The return value of Predicate types is always bool (true or false).
First The Predicate variables are assigned to lambda expressions. At this point they are valid predicates.
Then The program demonstrates how the Invoke method always returns true or false when it is called.
Syntax The => syntax separates the arguments from the method bodies. The right-hand side is evaluated to a Boolean result.
Note The two above lambdas return true if the argument is one, and if the argument is greater than four.
C# program that uses Predicate type instances
static void Main()
// This Predicate instance returns true if the argument is one.
<int> isOne =
x == 1;
// This Predicate returns true if the argument is greater than 4.
<int> isGreaterEqualFive =
(int x) =>
x >= 5;
// Test the Predicate instances with various parameters.
Predicate is often used with the List generic type. You can specify a lambda expression as the argument to certain List methods. The C# compiler then uses type inference.
List Find, Exists
Here We create a string array of 3 elements. Each string in the array has at least 4 characters.
TrueForAll We pass a lambda expression to TrueForAll, which receives a Predicate instance. The return value is a bool.
Result The Predicate returns true if the string has 3 or more chars. This is true for all items in the array, so TrueForAll returns true.
C# program that uses Predicate, List method
static void Main()
var items = new List<string>
// Use TrueForAll with a predicate.
item.Length >= 3))
Notes, lambda parsing. The right-hand side of a lambda acquires an implicit return value if this is indicated by the context. A Predicate must always have a Boolean return value.
The concept of predicate functions is explored in the book Structure and Interpretation of Computer Programs. Predicates are described as functions that must return true or false.
Note The type Predicate in the .NET Framework adheres to this definition. It is a specific implementation of the concept.
A summary. The term "predicate" has wide applicability in computer science. In C#, predicates are specified with lambda expressions where the result value is of type bool.
© 2007-2021 sam allen. send bug reports to firstname.lastname@example.org.