0
0
C Sharp (C#)programming~5 mins

Predicate delegate type in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A Predicate delegate helps you check if something is true or false about an item. It makes your code cleaner when you want to test conditions.

When you want to find items in a list that match a condition.
When you want to check if any item in a collection meets a rule.
When you want to filter data based on a true/false test.
When you want to pass a condition as a reusable piece of code.
When you want to simplify code that uses if-statements for checks.
Syntax
C Sharp (C#)
Predicate<T> predicateName = MethodName;

// or using lambda expression
Predicate<T> predicateName = item => condition;

T is the type of item you want to test.

The method or lambda must return true or false.

Examples
This example uses a method named IsEven to check if a number is even.
C Sharp (C#)
Predicate<int> isEven = IsEven;

bool IsEven(int number) {
    return number % 2 == 0;
}
This example uses a lambda expression to check if a string is longer than 5 characters.
C Sharp (C#)
Predicate<string> isLong = s => s.Length > 5;
Sample Program

This program creates a list of numbers and uses a Predicate delegate to find all even numbers. It then prints them.

C Sharp (C#)
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
        Predicate<int> isEven = n => n % 2 == 0;

        List<int> evenNumbers = numbers.FindAll(isEven);

        Console.WriteLine("Even numbers:");
        foreach (int num in evenNumbers) {
            Console.WriteLine(num);
        }
    }
}
OutputSuccess
Important Notes

You can use Predicate with any type, not just numbers or strings.

Predicate is often used with collection methods like FindAll, Exists, and RemoveAll.

Using lambda expressions makes your code shorter and easier to read.

Summary

Predicate delegate tests if an item meets a condition and returns true or false.

It helps write cleaner and reusable condition checks.

Commonly used with collections to find or filter items.