Predicate Delegate In C#

A common predefined generic type delegate in C# is the Predicate delegate. This delegate is located within the System namespace. It is designed to interact with methods that have specific criteria to evaluate whether a given parameter meets the specified conditions. Upon receiving a single input, the Predicate delegate produces a boolean outcome of either true or false.

Syntax:

It has the following syntax:

Example

public delegate bool Predicate <in P>(P obj);
  • public: This keyword indicates that the delegate can be accessed from any outside class or assembly in which it is included. It also indicates that any code that has access to the contained namespace or assembly can use the delegate.
  • delegate: This keyword indicates that a delegate type is being declared. A type that represents references to methods with a certain parameter list and return type is called a delegate.
  • bool: It describes the delegate's return type . In this case, it is bool, meaning that the delegate will provide a boolean value (true or false).
  • Predicate: The declaration of the delegate type is indicated by this name. The Predicate delegate type in .NET is frequently used to describe a method that checks to see whether an object meets a certain condition.
  • <in P>: The generic type parameter P for the delegate is specified in this part. The keyword before P denotes the contravariant nature of the P-type parameter. It indicates that you can pass a type that is derived from P, or even P itself, as an argument to the delegate in this case.
  • (P obj): The parameter list for the delegate is represented by (P obj). The delegate is only required to accept a single type P parameter called obj . A method that takes an argument of type P would be provided when using this delegate.
  • Common Use Cases

Several use cases of the Predicate Delegate in C# are as follows:

  • Filtering: Predicates are frequently used with methods like Find, FindAll, Exists, etc. to filter elements based on certain criteria.
  • Validation: Before processing data, predicates can be used to check it against certain requirements.
  • Searching: They are useful for searching through collections or arrays to find elements that match a particular condition.
  • Predicates can be passed as parameters to methods that take delegates, such as List methods, LINQ extension methods (Where, Any, All, etc.), and more.
  • They can also be assigned to delegate variables and used for method group conversions.
  • Example 1:

Let's consider an example to demonstrate the Predicate Delegates in C#.

Example

using System;
using System.Collections.Generic;
class C# Tutorial
{
    static void Main(string[] args)
    {
        // Create an integers list.
        List<int> elements = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12 };
        // Use a named method with a Predicate delegate.
        List<int> Even_Elements = elements.FindAll(IsEven);
        Console.WriteLine("The Even Elements are:");
        PrintList(Even_Elements);
        // Use the anonymous method of Predicate delegate.
        List<int> Odd_Elements = elements.FindAll(delegate (int num) { return num % 2 != 0; });
        Console.WriteLine("\nThe Odd Elements are:");
        PrintList(Odd_Elements);
        //Utilise a lambda expression as a predicate delegate.
        List<int> Multiples_Of_Four = elements.FindAll(num => num % 4 == 0);
        Console.WriteLine("\nThe Multiples of Four are:");
        PrintList(Multiples_Of_Four);
    }
    // Method to check if a number is even
    static bool IsEven(int q)
    {
        return q % 2 == 0;
    }
    // Method to print elements of a list
    static void PrintList(List<int> list)
    {
        foreach (int q in list)
        {
            Console.Write(q + " ");
        }
        Console.WriteLine();
    }
}

Output:

Output

The Even Elements are:
2 4 6 8 10 12 
The Odd Elements are:
1 3 5 7 9 11 
The Multiples of Four are:
4 8 12

Explanation:

Overall, this code showcases the flexibility of Predicate delegates in C#. It enables the use of named methods, anonymous methods, and lambda expressions for defining filtering conditions. The predicate delegate boosts the reusability and clarity of code, simplifying the process of selecting elements from a collection based on specific criteria.

Example 2:

Let's consider another instance to demonstrate the Predicate Delegates in C#.

Example

using System; 
class C# Tutorial 
{ 
static bool Uppermethod(string str_1)
{
    return str_1.Equals(str_1.ToUpper());
}
static void Main(string[] args)
{
    Predicate<string> isUpper = Uppermethod;
    bool ans = isUpper("HOW ARE U!!");
    Console.WriteLine(ans);
    }
}

Output:

Conclusion:

In summary, the code illustrates the process of checking if a specified string is in uppercase by leveraging delegates and converting method groups. This instance showcases the ability to use delegates to represent methods with matching signatures, allowing for versatile and adjustable method calls.

Input Required

This code uses input(). Please provide values below: