Explore Local Functions in C#

From C# 7.0, Microsoft has introduced Local Functions. We can define the local functions in the same as local variables. Local functions must define within the method, and those are available only for that method. Sometimes local functions can also call as inner or nested functions.

namespace ConsoleAppExp
{
    class Program
    {
        static void Main(string[] args)
        {
            ProcessData();
        }

        static void ProcessData()
        {
            int localSum(int a, int b)//local function
            {
                return a + b;
            }

            int sum = localSum(10, 20);
        }
    }
}

As shown above, we have defined local function localSum() in the ProcessData() method. And localSum() function will be available only for ProcessData() method.

Local Functions are useful when we have a requirement to call the specific functionality several times within the method, not anywhere else. In this type of scenario, we can define the local function within the method and call that local function wherever it required within the method. By defining the local functions, we can protect the functionality from the outside of the method.