In c#, Predicate is a built-in generic delegate, and it is useful to validate whether the input parameter meets the specified condition or not, and it’s same as Func and Action delegates to hold the reference of one or more methods.
The Predicate delegate can hold only the methods that take only one input parameter and returns a Boolean type value, either true or false.
From C# 3.0 onwards, the Predicate delegate will available automatically with the System namespace, and it will accept only one input parameter and returns a Boolean value, either true or false.
Following is the syntax of declaring the Predicate delegate with one input parameter in c#.
Here, the parameter in the angle bracket < >
will be considered as the input parameter, and the bool is the return type.
Following is the example of defining the Predicate delegate to hold the reference of one or more methods which is having the same method signature.
If you observe the above example, we created a Predicate delegate object (dlgt) with one input parameter (int) and assigned the method (IsGreaterthanZero) directly to the delegate object.
Here, the IsGreaterthanZero method is accepting only one input parameter and validating whether the input parameter is greater than zero or not. If it is greater than zero, it will return the value true; otherwise, it will return false.
When we execute the above example, we will get the result as shown below.
Every time while creating the predicate delegate, we must need to remember that we can include only one input parameter and the return type must be Boolean.
In c#, we can assign the anonymous method directly to the Predicate delegate by using the delegate keyword like as shown below.
If you observe the above code, we assigned an anonymous method directly to the Predicate delegate object (dlgt) using the delegate keyword.
In c#, we can also use Predicate delegate with lambda expressions. The lambda expressions are the shorthand way for declaring the anonymous methods.
Following are the important points which we need to remember about Predicate delegate in c#.