CodeBlanks Logo Icon CodeBlanks

Local functions

C# course · Beginner · Lesson 75/116

Learn to define functions inside a method.

Local functions

Starting with C# 7, a method can contain a local function. A local function can only be called from the method that surrounds it; it is not visible elsewhere. It is ideal for splitting a big computation into smaller pieces.

The declaration is like a normal method; only the static keyword is omitted. Example: int Square(int n) { return n * n; }.

Using local functions

Local functions can be declared before or after the outer method; the order of call does not matter. They can access the local variables of the outer method; this lets them share state without passing parameters from outside.

That way, helper computations that should not be called from outside are kept as local functions instead of separate class methods; the surface of the class stays clean.

Exercise Square with a local function

Define a static void Run() method. In its body declare the local function int Square(int n) { return n * n; } and print the result with Console.WriteLine(Square(5));. Call Run() from Main.

Show example solution
In the Run body add int Square(int n) { return n * n; } and Console.WriteLine(Square(5));, write Run(); in Main.
Example solution:
using System;

class Program
{
    static void Run()
    {
        // Declare Square as a local function and print its result
        int Square(int n) { return n * n; }
        Console.WriteLine(Square(5));
    }

    static void Main()
    {
        // Call Run
        Run();
    }
}

Test yourself

  1. Match each expression to its meaning

    void Outer()
    Outer method
    int Inner()
    Local function
    return;
    Exits flow
    static
    Class-level
  2. What does Square(4) print?

    static void Run()
    {
        int Square(int n) { return n * n; }
        Console.WriteLine(Square(4));
    }
    Run();
    • 16
    • 4
    • 8
    • 2
    Show answer

    16 — Correct. The local Square function returns 4*4 = 16.

  3. Local function declaration

    static void Run()
    {
        ____
        Console.WriteLine(Double(5));
    }
    Show answer
    static void Run()
    {
        int Double(int n) { return n * 2; }
        Console.WriteLine(Double(5));
    }

All lessons in Beginner