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

Why Predicate delegate type in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one method that adapts to any condition you dream up, without rewriting code?

The Scenario

Imagine you have a list of numbers and you want to find all the even ones. You try to write separate code for each condition, like checking if a number is even, greater than 10, or less than 5, repeating similar loops and checks everywhere.

The Problem

This manual way means writing lots of repeated code, which is slow and easy to mess up. Every time you want a new condition, you write a new loop or method, making your code bulky and hard to change.

The Solution

The Predicate delegate type lets you write one flexible method that takes any condition you want as a parameter. You just pass in the rule (the predicate), and the method uses it to pick items. This keeps your code clean, reusable, and easy to update.

Before vs After
Before
List<int> evens = new List<int>();
foreach(var n in numbers) {
  if(n % 2 == 0) evens.Add(n);
}
After
List<int> evens = numbers.FindAll(n => n % 2 == 0);
What It Enables

You can create powerful, reusable methods that work with any condition, making your programs smarter and simpler.

Real Life Example

Filtering a list of customers to find those who are active and live in a certain city by just changing the predicate condition without rewriting the whole search logic.

Key Takeaways

Manual filtering repeats code and is hard to maintain.

Predicate delegate lets you pass conditions as parameters.

This makes your code flexible, reusable, and easier to read.