Sobes.tech
Junior — Middle

How to distinguish a Predicate delegate from a Func delegate, and what are their main differences?

sobes.tech AI

Answer from AI

The main difference between Predicate and Func delegates in C# lies in their signatures and purpose:

  • Predicate<T> is a delegate that takes a parameter of type T and returns a bool. It is used for condition checks (predicates) on objects.

  • Func<T, TResult> is a generic delegate that takes a parameter of type T and returns a value of type TResult. Func is more versatile as TResult can be any type.

If Func returns bool and takes one parameter, it is functionally equivalent to Predicate.

Example:

Predicate<int> isPositive = x => x > 0;
Func<int, bool> isPositiveFunc = x => x > 0;

bool result1 = isPositive(5);       // true
bool result2 = isPositiveFunc(5);   // true

Thus, Predicate is a specialized delegate for conditions, and Func is a universal delegate for functions with return values.

How to distinguish a Predicate delegate from a Func… - sobes.tech