Skip to content

Generic delegates Action Func Predicate

Context: The .NET framework provides generic delegates for common signatures, eliminating the need to declare custom delegates.

For methods that return void. Up to 16 parameters.

Action print = () => Console.WriteLine("Hello");
Action<string> log = (msg) => Console.WriteLine(msg);
Action<int, int> addAndPrint = (a, b) => Console.WriteLine(a + b);

For methods that return a value. Last type parameter is the return type.

Func<int> getNumber = () => 42;
Func<string, int> getLength = (s) => s.Length;
Func<int, int, int> add = (a, b) => a + b;

Returns bool. Equivalent to Func<T, bool>.

Predicate<int> isEven = (x) => x % 2 == 0;
bool result = isEven(4); // true

LINQ queries: Where uses Func<TSource, bool> (a predicate). ForEach uses Action<T>. Select uses Func<TSource, TResult>.

Example: Enumerable.Where expects a Func<TSource, bool> delegate.