C#

C# Predicate

Predicate is a pre-built delegate in the .NET framework class library. Delegates are used to store method which has same parameters and return types as specify in the delegate type. Predicate is a generic delegate. It takes one parameter and returns a boolean value.

Predicate delegate is used for check whether a parameter meets specify condition or not.

Below is the syntax of Predicate.

public delegate bool Predicate<in T>(T obj);

In the delegate instance, we can store only that method which takes only one parameter and returns a bool data type.

Predicate Example

In the below example, I have created a method which check whether a string parameter is uppercase or not.

static void Main(string[] args)
{
    Predicate<string> checkUpper = IsUpperCase;
    bool result = checkUpper("KAPIL");
    Console.WriteLine(result); //Print True

    result = checkUpper("Hello");
    Console.WriteLine(result); //Print False
}

static bool IsUpperCase(string arg1)
{
    foreach(var chr in arg1)
    {
        if(!char.IsUpper(chr))
        {
            return false;
        }
    }
    return true;
}

We have created a method IsUpperCase which takes arg1 as single parameter and returns boolean true or false. It enumerates over arg1 and check is every character is uppercase or not. We declared a Predicate<string> checkUpper and assigned IsUpperCase method to it. We call checkUpper delegate with “KAPIL”. It returns True in the result variable.

We again call checkUpper predicate delegate with “Hello” parameter. It returns false in the result variable.

Predicate with Lambda Expression

Instead of passing a method in the Predicate delegate, we can assign lambda expression. Lambda expression is used for writing anonymous function that we can pass as a parameter.

Lambda expression has a special syntax. We have to write all parameters on left side in parenthesis. In middle we have lambda operation =>. On the right side, we have body of the lambda expression.

Below is the example of Predicate using lambda expression.

static void Main(string[] args)
{
    Predicate<string> checkUpper = (arg1) =>
        {
            foreach (var chr in arg1)
            {
                if (!char.IsUpper(chr))
                {
                    return false;
                }
            }
            return true;
        };

    bool result = checkUpper("DELEGATE");
    Console.WriteLine(result); //Print True

    result = checkUpper("delegate");
    Console.WriteLine(result); //Print False
}

We have created an instance of Predicate<string>. We created a lambda expression and assign it directly to delegate. In the next line, we call checkUpper delegate using “DELEGATE” parameter which returns True.