Junior — Middle
What is the difference between Func and Predicate delegates in C#?
sobes.tech AI
Answer from AI
In C#, delegates Func and Predicate are used to represent methods, but they have different purposes and signatures:
-
Func<T, TResult>— a delegate that takes one or more parameters and returns a value of typeTResult. It can have from 0 to 16 parameters, with the last parameter always being the return type. -
Predicate<T>— a delegate that takes a single parameter of typeTand returns abool. It is used for condition checking (predicates).
Thus, Predicate<T> is a special case of Func<T, bool>. For example:
Func<int, string> funcExample = x => x.ToString();
Predicate<int> predicateExample = x => x > 0;
Predicate is convenient for methods where you need to check a condition and get a boolean result, such as filtering collections.