Introduction
This article introduces you to how to use Func, Action, and Local Function in C# 7 language. These methods are used to hide a method in another method or nested method. Func and Action are predefined generic delegates, which take zero to sixteen input parameters.
The basic difference between both is that Func always returns a value while Action doesn’t return a value.
Local function can be defined in the body of any method.
Both Func and Action delegates must be defined before they are called, while the Local function can be defined later in the method.
This article’s code examples are available at MSDN Sample.
Func
The Func<T, TResult> is a predefined generic delegate. It has zero to sixteen parameters and one out parameter. It always returns a value. As it is a function, the first type parameters are the input arguments and the final type parameter is the return value. Func delegate type can be used with an anonymous method or lambda expression.
Here, we create an example, that checks whether a number is a prime number or not. This example uses Func<T, TResult> with a lambda expression to check the prime number. The code snippet given below can be used for the same.
using static System.Console;
using System;
namespace PrimeNumberApp
{
class Program
{
static void Main(string[] args)
{
Func<int, bool> checkPrimeNumber = x =>
{
bool isPrime = false;
int i;
for (i = 2; i <= x - 1; i++)
{
if (x % i == 0)
{
isPrime = false;
break;
}
}
if (i == x)
{
isPrime = true;
}
return isPrime;
};
WriteLine("Enter a number");
int number = Convert.ToInt32(ReadLine());
bool isPrimeNumber = checkPrimeNumber(number);
WriteLine($"{number} is {(isPrimeNumber ? "" : "not")} prime number");
ReadKey();
}
}
}
As per the code snippet given above, Func<int, bool> has two parameters, the first parameter is an input parameter, while another is out parameter. It takes an int value as an input argument and returns a bool value.
Here, an input parameter named x goes to an anonymous function, which returns true, if the input is a prime number or not.
Now, run the Application. It shows the result as per the image given below.

Figure 1: Output
Action
The Action is a predefined delegate, which has no return type. In other words, its return type is void. All the parameters of the Action delegate are considered the input parameters. It is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list.



Join the conversation! Your thoughts help the community grow.