C# - Predicate Delegate
Predicate
is the delegate like Func and Action delegates. It represents a method containing a set of criteria and checks whether the passed parameter meets those criteria. A predicate delegate methods must take one input parameter and return a boolean - true or false.
The Predicate
delegate is defined in the System
namespace, as shown below:
Predicate signature: public delegate bool Predicate<in T>(T obj);
Same as other delegate types, Predicate
can also be used with any method, anonymous method, or lambda expression.
static bool IsUpperCase(string str)
{
return str.Equals(str.ToUpper());
}
static void Main(string[] args)
{
Predicate<string> isUpper = IsUpperCase;
bool result = isUpper("hello world!!");
Console.WriteLine(result);
}
An anonymous method can also be assigned to a Predicate delegate type as shown below.
static void Main(string[] args)
{
Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
bool result = isUpper("hello world!!");
}
A lambda expression can also be assigned to a Predicate delegate type as shown below.
static void Main(string[] args)
{
Predicate<string> isUpper = s => s.Equals(s.ToUpper());
bool result = isUpper("hello world!!");
}
- Predicate delegate takes one input parameter and boolean return type.
- Anonymous method and Lambda expression can be assigned to the predicate delegate.