Sobes.tech
Junior — Middle

Kuidas eristada Predicate tüüpi delegeeti Func tüüpi delegeedist ning millised on nende peamised erinevused?

sobes.tech AI

Vastus AI-lt

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

  • Predicate<T> — is a delegate that takes a parameter of type T and returns a bool. It is used for checking a condition (predicate) on an object.

  • 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 a single 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

Therefore, Predicate is a specialized delegate for conditions, while Func is a universal delegate for functions with a return value.