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 toMain
. -
You cannot call
CalculateSum
from outsideMain
.
π 3. Advantages of Local Functions
-
Encapsulation
- Keeps helper methods private to the containing method.
-
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
}
-
Improved readability
- Keeps related logic close together, avoiding cluttering the class with small private methods.
-
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
Feature | Local Function | Lambda Expression |
---|---|---|
Syntax | int Add(int a,int b) | (a,b) => a+b |
Named function | β | β (anonymous) |
Can use ref /out | β | β |
Readability | Good for multi-line | Good 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.