Let’s go through local functions, introduced in C# 7, which let you define a function inside another function.


πŸ“Œ 1. What Are Local Functions?

  • Local functions are methods defined inside another method.

  • They cannot be called from outside the containing method.

  • Useful for helper logic that is only relevant within the enclosing method.


πŸ“Œ 2. Syntax Example

class Program
{
    static void Main()
    {
        Console.WriteLine("Result: " + CalculateSum(5, 10));
 
        int CalculateSum(int a, int b)
        {
            return a + b; // local function
        }
    }
}
  • CalculateSum is local to Main.

  • You cannot call CalculateSum from outside Main.


πŸ“Œ 3. Advantages of Local Functions

  1. Encapsulation

    • Keeps helper methods private to the containing method.
  2. Access to local variables

    • Can access variables from the outer method without passing them explicitly.
static void Main()
{
    int factor = 2;
 
    int Multiply(int x)
    {
        return x * factor; // accesses outer variable
    }
 
    Console.WriteLine(Multiply(5)); // Output: 10
}
  1. Improved readability

    • Keeps related logic close together, avoiding cluttering the class with small private methods.
  2. Performance

    • No delegate allocation required (unlike lambdas) unless captured.

πŸ“Œ 4. Local Functions with Parameters & Return Types

static int Fibonacci(int n)
{
    if (n < 2) return n;
 
    int Fib(int k) // local recursive function
    {
        if (k < 2) return k;
        return Fib(k - 1) + Fib(k - 2);
    }
 
    return Fib(n);
}
 
Console.WriteLine(Fibonacci(5)); // Output: 5
  • Local functions can be recursive.

πŸ“Œ 5. Comparison to Lambda Expressions

FeatureLocal FunctionLambda Expression
Syntaxint Add(int a,int b)(a,b) => a+b
Named functionβœ…βŒ (anonymous)
Can use ref/outβœ…βŒ
ReadabilityGood for multi-lineGood for short expressions

βœ… Summary:

  • Local functions are methods inside methods.

  • They cannot be accessed outside the containing method.

  • Useful for encapsulation, readability, and helper logic.

  • Can access outer variables, be recursive, and take parameters.