Codectionary / Developer documentation / C#

Static Local Functions

Local functions hide helper logic inside the containing member. Marking one static prevents accidental capture of surrounding variables. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

Local functions hide helper logic inside the containing member. Marking one static prevents accidental capture of surrounding variables. Use a .NET 8+ console project; replace Program.cs with this C# example.

Square is available only inside TotalSquares. Its static modifier ensures all required data arrives through parameters.

Syntax

static int Helper(int value) => value * value;

Examples

Static Local Functions

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
static int TotalSquares(int first, int second)
{
    static int Square(int value) => value * value;
    return Square(first) + Square(second);
}
Console.WriteLine(TotalSquares(3, 4));
  1. Expected output: 25
  2. Square is available only inside TotalSquares. Its static modifier ensures all required data arrives through parameters.
  3. Use a local function when the helper belongs to one algorithm.

Best practices

  • Use a local function when the helper belongs to one algorithm.
  • Prefer static helpers when they do not need captured state.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading