How do the built-in Func<>, Action<>, and Predicate<T> generic delegate types differ, and when would you use each?
Short answer
Func represents a method that returns a value (the LAST type parameter is always the return type); Action represents a method with NO return value (void); Predicate is specifically a method taking one argument and returning bool, functionally equivalent to Func but used…
Advertisement
AModel answer
Func<T1,...,TResult> represents a method that returns a value (the LAST type parameter is always the return type); Action<T1,...> represents a method with NO return value (void); Predicate<T> is specifically a method taking one argument and returning bool, functionally equivalent to Func<T, bool> but used idiomatically in older/certain collection APIs like List<T>.Find().
Func<int, int, int> add = (a, b) => a + b;
Action<string> log = message => Console.WriteLine(message);
Predicate<int> isEven = n => n % 2 == 0;
List<int> numbers = new() { 1, 2, 3, 4 };
int firstEven = numbers.Find(isEven); // 2Real-world example
Choosing the right built-in delegate type for a method parameter instead of always declaring a custom delegate type.
Likely follow-ups
- Why does Predicate<T> still exist as a separate type when Func<T, bool> could express the same shape?
Related topics