๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# Func and Action

Func, Action, and Predicate are built-in delegate types. They cover most delegate needs without a new type declaration.

Func holds a method

Func<int, int, int> takes two ints and returns an int. The variable holds the Add method.

using System;

class Program
{
    static int Add(int a, int b)
    {
        return a + b;
    }

    static void Main(string[] args)
    {
        Func<int, int, int> add = Add;
        Console.WriteLine(add(5, 6));
    }
}

Action prints a message

Action<string> takes one string and returns nothing. The variable holds a printing method.

using System;

class Program
{
    static void PrintMessage(string text)
    {
        Console.WriteLine(text);
    }

    static void Main(string[] args)
    {
        Action<string> show = PrintMessage;
        show("Ready");
    }
}

Predicate answers true or false

Predicate<int> takes one int and returns a bool. The lambda tests whether the value is above 10.

using System;

class Program
{
    static void Main(string[] args)
    {
        Predicate<int> isBig = n => n > 10;
        Console.WriteLine(isBig(15));
        Console.WriteLine(isBig(4));
    }
}

FindAll filters a list

FindAll applies the predicate to each item. The matching items print one per line.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 3, 8, 12, 5, 20 };
        List<int> big = numbers.FindAll(n => n > 10);
        foreach (int number in big)
        {
            Console.WriteLine(number);
        }
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        Func<int, int> square = n => n * n;
        Action<int> show = n => Console.WriteLine(n);
        show(square(6));
        show(square(3));
    }
}

Key points

  • Func is a built-in delegate type for methods that return a value.
  • The last type in Func is the return type.
  • Action is a built-in delegate type for methods that return nothing.
  • Predicate is a built-in delegate type that returns a bool.
  • FindAll returns the list items that pass a predicate.

In this example, the Func lambda squares its input. The Action lambda prints the value it receives. The calls print 36 and then 9.

Note

These types remove the need to declare a delegate type first.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which built-in type always returns a bool?