Local functions

A function inside a method

A method may declare a function of its own. It has a name, parameters and a return type like any other, and only the method that declares it can call it.

Console.WriteLine(Factorial(5)); Console.WriteLine(Fib(10)); static int Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1); static int Fib(int n) => n < 2 ? n : Fib(n - 1) + Fib(n - 2);

dotnet run

120
55

The two functions are local functions of the generated entry point, and both call themselves. A local function is a better home than a lambda for a named helper that is used twice in one method: it appears in a stack trace under its own name, it can be recursive without a delegate, and it costs no allocation when it captures nothing.

static local functions

A static local function may not read the variables of the enclosing method. That restriction is a promise to the reader: the result of the function depends on its arguments only.

static int Square(int n) => n * n; Console.WriteLine(Square(5));

dotnet run

25

A local function without static may capture, and the compiler then builds a closure object to hold the variable. With static there is nothing to close over, so the compiler generates a plain method and the call is a direct one.

The closure

A local function that reads or writes a variable of its method shares that variable, not a copy of it:

int calls = 0; int Twice(int n) { calls++; return n * 2; } Console.WriteLine(Twice(2)); Console.WriteLine(Twice(3)); Console.WriteLine($"calls: {calls}");

dotnet run

4
6
calls: 2

calls is a local of the method, and the function incremented the same variable twice. The compiler puts such a variable into a generated class, which is why a captured variable outlives the frame it was declared in and why a local function that captures is a delegate-like allocation.

A capture also keeps the variable alive. A lambda or local function handed to something that outlives the method keeps its captured variables with it, which is the usual cause of a memory leak in an event handler.

Recursion

Both functions of the first program are recursive, and Fib is the expensive kind: every call makes two more, so the number of calls grows exponentially and Fib(40) takes about a second on this machine. The loop version is linear, and the part on performance measures both with a stopwatch.

A recursion that never reaches its base case ends with a StackOverflowException, which cannot be caught: the process is gone before any handler could run. A recursive method should therefore be checked for its base case first, as both of these do.

Exercises

  1. Make Factorial a static local function and then make it read calls. Read the error.
  2. Write Fib with a loop and compare the time of Fib(30) in both forms with a stopwatch.
  3. Write a local function that reverses a string by calling itself on the tail and stops at the empty string.
  4. Remove the base case of Factorial and call it with 5. What happens, and can the program report it?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Where can a local function be called from?

    Answer

    Only the method that declares it

    The name lives in the scope of the declaring method, so nothing outside it can see the function.

  2. What does a static local function refuse to do?

    Answer

    Read or write the variables of the enclosing method

    static means no capture, so the function may use only its parameters and its own locals.

  3. What does this program print? Console.WriteLine(Factorial(4)); static int Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1);

    Answer

    24

    The product of 4, 3, 2 and 1 is 24, and a local function may call itself by name.

  4. What does a closure capture?

    Answer

    The variable itself, so a write is visible to the enclosing method

    The compiler hoists the captured variable into a generated class, so both sides share one storage slot.

  5. What does this program print? int calls = 0; int Twice(int n) { calls++; return n * 2; } Console.WriteLine(Twice(2)); Console.WriteLine(Twice(3)); Console.WriteLine(calls);

    Answer

    4 / 6 / 2

    Both calls increment the same captured variable, so the count is 2 after the two prints.

  6. Which function is more expensive, Fib(n) as a double recursion or as a loop?

    Answer

    The double recursion: its calls grow exponentially

    Each call makes two more, so the count doubles per step, while the loop walks the sequence once.

  7. What happens when a recursion never reaches its base case?

    Answer

    StackOverflowException ends the process and cannot be caught

    The stack runs out before a handler could run, which is why the base case is checked first.

  8. What does this program print? Console.WriteLine(Square(5)); static int Square(int n) => n * n;

    Answer

    25

    A static local function is allowed and returns the square of its argument.

  9. Why does a local function show up better in a stack trace than a lambda?

    Answer

    It has a name, so the frame names the function that failed

    The name is part of the generated method, while a lambda appears as a generated method with a number.

  10. When is a local function cheaper than a delegate?

    Answer

    When it captures nothing, because the call is direct

    Without a capture the compiler emits a plain static method, so no delegate object is created.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev