Share via


C# 7: Func, Action And Local Function

Introduction

This article introduces 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 defines in the body of any method.

Both Func and Action delegates must be defined before they are called, while a Local function can be defined later in the method.

This article’s code examples are available at MSDN Sample.

Func

The Func 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, 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, which checks whether a number is a prime number or not. This example uses Func with a lambda expression to check 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 is given above, Func 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 is 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 Action delegate are considered as the input parameters. It is more commonly used for things like List.ForEach: execute the given action for each item in the list.

Here, we create an example, which prints a Fibonacci series. This example uses Action with a lambda expression to print a Fibonacci series. The code snippet given below can be used for the same.

using System;  
using static  System.Console;  
   
namespace FibonacciSeriesApp  
{  
    class Program  
    {  
        static void  Main(string[] args)  
        {  
            Action<int> GetFibonacciSeries = x =>  
             {  
                 int starter = 0, next = 1, number = 0;  
                 Write($"{starter} {next}");  
                 for (int i = 2; i < x; i++)  
                 {  
                     number = starter + next;  
                     Write($" {number}");  
                     starter = next;  
                     next = number;  
                 }  
             };  
            WriteLine("Enter a length");  
            int num = Convert.ToInt32(ReadLine());  
            GetFibonacciSeries(num);  
            ReadKey();  
        }        
    }  
}

As per the code snippet is given above, Action has one parameter, which takes an input argument as int type.

Here, an input parameter named x goes to an anonymous function, which prints a Fibonacci series of x length.

Now, run the Application. It shows the result, as shown in the image given below.

Figure 2: Output

Local Function

The Local function is a new concept introduced in C# 7. The Local function can be defined in the body of any method and property’s getter and setter. All the arguments and the local variables in the outer function are in scope of a local function. These local functions can use ref and out parameters.

Here, we create an example, which calculates a factorial number of a given number. This example uses a local function named GetFactorial to calculate factorial of the number. The code snippet given below can be used for the same.

using System;  
using static  System.Console;  
   
namespace LocalFunctionApp  
{  
    class Program  
    {  
        static void  Main(string[] args)  
        {  
            WriteLine("Enter a number to calculate factorial");  
            int num = Convert.ToInt32(ReadLine());  
            long fact = GetFactorial(num);  
            WriteLine($"{num} factorial is {fact}");  
            long GetFactorial(int number)  
            {  
                return number == 0 ? 1 : number * GetFactorial(number - 1);  
            }  
            ReadKey();  
        }  
    }  
}

As per the code snippet is given above, GetFactorial is a local function in the Main method, which has a parameter and returns a long type value.

Now, run the Application. It shows the result, as shown below.

Figure 3: Output

Download

We can download the source code for these examples from MSDN Sample. The link, which can be referred is C# 7: Func, Action and Local Function.

Conclusion

These delegates and function use a nested method, which makes the code readable. The Action method doesn’t have a return type, while Func has at least one return value. The local function can be used same as other methods but it can’t be static.

See Also

There are some more article related C#. These are:

  1. C# 7: Tuple
  2. C#: Why Use Property
  3. C#: Dependency Injection In Console Application