Func, Action, Predicate
Func, Action, and Predicate are ready-made delegate types: Func gives back an answer, Action just does something, and Predicate answers yes or no. They save you from creating your own.
In this page:
Syntax
Func<type1, type2, ReturnType> func = (a, b) => expression; // returns a value
Action<type> action = value => statement; // returns nothing
Predicate<type> predicate = value => condition; // returns bool
Func, Action, Predicate
Func<T,...,TResult> represents a method that returns a value, Action<T,...> represents one that returns nothing, and Predicate<T> represents one that takes a T and returns bool.
These built-in generic delegate types save you from declaring a custom delegate type for common shapes. They're used extensively throughout LINQ and collection methods.
Note:
Func<int, int, int> means "takes two ints, returns an int" — the last type parameter is always the return type.Example: Func, Action, Predicate
using System;
class Program
{
static void Main(string[] args)
{
Func<int, int, int> add = (a, b) => a + b;
Action<string> print = msg => Console.WriteLine(msg);
Predicate<int> isEven = n => n % 2 == 0;
Console.WriteLine(add(4, 5));
print("Hello from Action");
Console.WriteLine(isEven(10));
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
Funcwhen the method returns nothing, whenActionis the right type. - Forgetting that the last type argument of
Funcis the return type. - Using
Predicate<T>and expecting it to return something other than bool.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: