In C#, a Predicate is a built-in delegate type used to represent a method that takes one input parameter and returns a boolean value (true or false). It is widely used for testing conditions, especially in filtering data with collections.
Example: Predicate with a Lambda Expression
CSharp
Predicate<int> isEven = n => n % 2 == 0;
Console.WriteLine(isEven(10));
Console.WriteLine(isEven(7));
Output:
True
False
The Predicate<int> delegate takes an integer and checks if it is even. It returns true for 10 and false for 7.
Key Points
- Predicate delegates always return a bool.
- Useful for conditions, filtering and validation.
- Frequently used with collection methods like Find, FindAll, Exists, RemoveAll.
- Provides cleaner, reusable and testable condition logic.
Syntax
public delegate bool Predicate<in T>(T obj);
- Always takes exactly one parameter of type T.
- Always returns a bool (true or false).
Example 1: Predicate with a Named Method
CSharp
class Program {
static bool CheckPositive(int number) {
return number > 0;
}
static void Main() {
Predicate<int> isPositive = CheckPositive;
Console.WriteLine(isPositive(5));
Console.WriteLine(isPositive(-3));
}
}
Output:
True
False
The method CheckPositive matches the Predicate signature (takes one parameter, returns bool). So it can be directly assigned to a Predicate delegate.
Example 2: Predicate with Collections
Predicates are very useful in collection methods like List<T>.Find, FindAll, Exists and RemoveAll.
C#
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
Predicate<int> isEven = n => n % 2 == 0;
var firstEven = numbers.Find(isEven);
var allEven = numbers.FindAll(isEven);
Console.WriteLine($"First Even: {firstEven}");
Console.WriteLine("All Even Numbers:");
allEven.ForEach(n => Console.WriteLine(n));
Output:
First Even: 2
All Even Numbers:
2
4
6
- Find -> Returns the first element matching the condition.
- FindAll -> Returns all elements matching the condition.
- The Predicate makes it easy to pass conditions as reusable delegates.
Example 3: Predicate with Custom Objects
C#
class Student {
public string Name { get; set; }
public int Marks { get; set; }
}
class Program {
static void Main() {
List<Student> students = new List<Student> {
new Student { Name = "Alice", Marks = 85 },
new Student { Name = "Bob", Marks = 40 },
new Student { Name = "Charlie", Marks = 60 }
};
Predicate<Student> hasPassed = s => s.Marks >= 50;
var passedStudents = students.FindAll(hasPassed);
Console.WriteLine("Passed Students:");
passedStudents.ForEach(s => Console.WriteLine($"{s.Name} - {s.Marks}"));
}
}
Output:
Passed Students:
Alice - 85
Charlie - 60
Here the Predicate checks whether a student has marks greater than or equal to 50. The FindAll
method uses this Predicate to return only passing students.
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers