0
0
CsharpConceptBeginner · 3 min read

Predicate Delegate in C#: What It Is and How to Use It

In C#, a Predicate<T> is a delegate that represents a method that takes an object of type T and returns a bool. It is commonly used to test if an object meets a certain condition, returning true or false.
⚙️

How It Works

Think of a Predicate<T> as a question you ask about an object. You give it something, and it answers either "yes" (true) or "no" (false). For example, you might ask if a number is even or if a string contains a certain word.

Under the hood, Predicate<T> is a delegate type, which means it holds a reference to a method that matches its signature: it takes one parameter of type T and returns a bool. This lets you pass around these methods as variables and use them wherever you need to check conditions.

This is very useful when working with collections, like lists, where you want to find or filter items based on some rule without writing repetitive code.

💻

Example

This example shows how to use a Predicate<int> to find if a list contains an even number.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 3, 5, 8, 9 };

        // Define a Predicate that checks if a number is even
        Predicate<int> isEven = n => n % 2 == 0;

        // Use the Find method with the Predicate
        int found = numbers.Find(isEven);

        if (found != 0)
            Console.WriteLine($"First even number found: {found}");
        else
            Console.WriteLine("No even number found.");
    }
}
Output
First even number found: 8
🎯

When to Use

Use Predicate<T> when you want to check if items in a collection meet a specific condition. It helps you write cleaner and reusable code by separating the condition logic from the collection operations.

Common real-world uses include:

  • Finding or filtering items in lists or arrays.
  • Validating input data against rules.
  • Passing conditions to methods like List<T>.Find, RemoveAll, or Exists.

It’s like having a flexible question you can ask many times without rewriting the question each time.

Key Points

  • Predicate<T> is a delegate that returns a bool for an input of type T.
  • It is mainly used to test conditions on objects.
  • Commonly used with collection methods like Find, Exists, and RemoveAll.
  • Helps keep code clean by separating condition logic from collection operations.

Key Takeaways

Predicate is a delegate that takes an object of type T and returns a bool indicating a condition.
It is useful for checking if items in collections meet specific criteria.
You can pass Predicate to methods like List.Find to search or filter items easily.
Using Predicate helps write cleaner and reusable code by separating condition logic.