← Back to C# Course | Chapter 12: Delegates & Events | Lesson 4 of 6

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:

  1. Func, Action, Predicate
Syntax
csharp
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

markup
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));
    }
}
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
  1. Using Func when the method returns nothing, when Action is the right type.
  2. Forgetting that the last type argument of Func is the return type.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.