c sharp

What is Predicate delegate in C#

The C# programming language’s Predicate Delegate is a potent feature that allows you to send a specific method as an argument to another function. It is extensively used in various programming scenarios, including filtering collections, searching arrays, and conditional programming.

In this article, we will explore the basics of predicate delegates in C# and provide examples to help you get started.

What is a Predicate delegate in C#

In C#, delegates are a way of providing methods as parameters in other methods. A predicate delegate is a particular type of delegate that is used to evaluate whether an object satisfies a certain condition or not. This type of delegate is commonly used with LINQ queries and other data processing operations, where filtering and selection of data are needed.

The syntax of the predicate delegate is given below.

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

 

The predicate delegate accepts a generic type argument T indicating the type of the input parameter.

Return Value of Predicate delegate

The predicate delegate is a type of delegate that is defined to take a single input parameter and return a Boolean result. This Boolean result indicates whether the input parameter satisfies the condition that the delegate is responsible for evaluating. In C#, the System.Predicate delegate is commonly used for this purpose.

Predicate delegate in C#

Consider the following code, which defines a predicate delegate and a method that uses it to filter a list of integers:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> values = new List<int> { 1, 2, 5, 3, 9, 7, 9, 8};
        List<int> oddNumbers = values.FindAll(oddNum);
        Console.WriteLine(string.Join(",", oddNumbers));
    }

    static bool oddNum(int number)
    {
        return number % 2 != 0;
    }
}

 

In the above code, the predicate delegate is specified as a method called oddNum, which takes an integer input parameter and returns a Boolean result indicating whether the input parameter is even. The FindAll method of the List<int> class is then used to filter the list of numbers by sending the IsEven function to the Predicate delegate as a parameter.

How to Use Predicate delegate in C#

There are three ways to use predicate delegate in C#.

1: Predicate delegate with Anonymous Method

One way to make use of the Predicate delegate is to create an anonymous method that meets the delegate’s signature. For instance, the preceding code may be rewritten as follows:

using System;
using System.Collections.Generic;

class myClass
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        List<int> evenNumbers = numbers.FindAll(delegate(int number) { return number % 2 == 0; });
        Console.WriteLine(string.Join(",", evenNumbers));
    }
}

 

In the code above, an anonymous method (a code block that starts with the keyword “delegate” and ends with the closing brace “}) is implemented that receives an integer input argument and returns a Boolean value indicating whether the input parameter is even. The anonymous method is then passed as a parameter to the predicate delegate, which is then used to filter the list of even numbers.

2: Predicate delegate with Lambda Expressions

The predicate delegate can also be used with lambda expressions “=>” to define anonymous methods more compactly. For example, the preceding code may be rewritten as follows using a lambda expression:

using System;
using System.Collections.Generic;

class myClass
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        List<int> evenNumbers = numbers.FindAll(number => number % 2 == 0);
        Console.WriteLine(string.Join(",", evenNumbers));
    }
}

 

In the code above, a lambda expression is used to define an anonymous method that receives an integer input argument and returns a Boolean value indicating whether the input parameter is even or odd. The FindAll method is then used to filter the list of integers by sending the lambda expression to the Predicate delegate as a parameter.

Output

3: Predicate delegate with LINQ Queries

Predicate delegates are also used with LINQ queries, where they are used to filter and similarly select data. Consider the following code, which filters a collection of strings using a lambda expression and the Where method of the Enumerable class:

using System;
using System.Linq;
 
class Program
{
    static void Main()
    {
        string[] words = { "linux", "hint", "predicate", "delegate", "lambda" };
        var longWords = words.Where(word => word.Length > 5);
        Console.WriteLine(string.Join(",", longWords));
    }
}

 

In this above code, the Where() method is used to filter the original list based on a predicate delegate that checks whether the length of the string is greater than 5. The result is a new Enumerable that contains only those strings with a length greater than 5.

Output

Conclusion

The predicate delegate is a useful feature in C# programming that allows methods to be passed as parameters to other methods, making code more flexible and easier to maintain. Predicate delegate can be used with anonymous methods, lambda expressions, and LINQ queries to filter and select data.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.