0Pricing
C# Academy · Lesson

Static Local Functions

Prevent captures for clarity and performance.

Static Local Functions

Marking a local function static forbids it from capturing any enclosing variables or this. This makes the function self-contained, clearer, and free of hidden closure allocations.

Declaring a static Local Function

Add the static modifier before the return type. The function may still take parameters and return values; it just cannot reach outer locals.

using System;

public class Program
{
    public static void Main()
    {
        static int Square(int n) => n * n; // captures nothing

        Console.WriteLine(Square(6));
    }
}

All lessons in this course

  1. Declaring Local Functions
  2. Closures and Captured Variables
  3. Static Local Functions
  4. Local Functions vs Lambdas
← Back to C# Academy