C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
The Predicate type in the C# language stores a method that receives one parameter and returns one value of true or false. And it is often used with lambda expression syntax.
Example. We look at a program that uses two Predicate instances with the parameterized type of integer. The return value of Predicate types is always bool (true or false). The Predicate types are assigned to lambda expressions.
Then: The program then demonstrates how the Invoke method always returns true or false when it is called in the source text.
C# program that uses Predicate type instances using System; class Program { static void Main() { // // This Predicate instance returns true if the argument is one. // Predicate<int> isOne = x => x == 1; // // This Predicate returns true if the argument is greater than 4. // Predicate<int> isGreaterEqualFive = (int x) => x >= 5; // // Test the Predicate instances with various parameters. // Console.WriteLine(isOne.Invoke(1)); Console.WriteLine(isOne.Invoke(2)); Console.WriteLine(isGreaterEqualFive.Invoke(3)); Console.WriteLine(isGreaterEqualFive.Invoke(10)); } } Output True False False True
In this example, the lambda expression syntax is used to specify the function body for the Predicates. The => syntax separates the arguments from the method bodies. The right-hand side is evaluated to a Boolean result.
In lambda expressions, the right-hand side of the expression acquires an implicit return value if this is indicated by the context. The Predicate type must always have a Boolean return value.
Note: The two above lambdas return true if the argument is one, and if the argument is greater than four.
Finally: The program executes the Invoke instance method on the Predicate types to demonstrate the functionality.
List. 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 to resolve the lambda expression to the correct Predicate type.
Note: You can store the Predicate in a field or local variable. Please see the articles on the Find and RemoveAll methods for details.
Concept. The concept of predicate functions is explored in the book Structure and Interpretation of Computer Programs. In the book, predicates are described as functions that must return true or false.
This is the meaning of the term predicate when describing functions. The type Predicate in the .NET Framework adheres to this definition, but is just a specific implementation of the concept.
Summary. We looked at the Predicate type. We saw how it is applied correctly to lambda expressions where the result value is of type bool. The method body on the right-hand side of a lambda expression is evaluated in a boolean context.
And: The term predicate, as a method returning true or false, has wide applicability in computer science.