Loading...

A predicate is a delegate like Func and Action delegates. It included in System namespace. It represents a method that contains a set of criteria and checks whether the passed parameter meets those criteria or not. A predicate delegate methods must take one input parameter and return a boolean.

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);
}


Predicate delegate with anonymous method

static void Main(string[] args)
{
    Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
    bool result = isUpper("hello world!!");
}


Predicate delegate with lambda expression

static void Main(string[] args)
{
    Predicate<string> isUpper = s => s.Equals(s.ToUpper());
    bool result = isUpper("hello world!!");
}


Things to be remember when using Predicate delegate:

  1. Predicate delegate takes one input parameter and boolean return type.
  2. Anonymous method and Lambda expression can be assigned to the predicate delegate.