skip to content

In a C# code review, why mark a local function static, and what does the compiler then reject and still allow inside it?

level: seniorimportance: should knowfreq 38%

answer

  1. C# 8 modifier
  2. no enclosing locals, parameters or this
  3. CS8421 and CS8422
  4. constants, statics and nameof still allowed
  5. emitted as a static method

basics

~20 s

A static local function (C# 8) cannot capture: referencing an enclosing local or parameter raises CS8421, and this, base or an instance member raises CS8422. Constants, static members and nameof still work, so it never builds a closure.

solid answer

~40 s

Marking a local function `static`, allowed since C# 8, turns "this helper captures nothing" from a hope into a compiler-checked rule. Any reference to an enclosing local or parameter (including a primary constructor parameter) is error CS8421, and any use of `this`, `base` or an instance member, explicit or implicit, is CS8422. It may still use `const` values, static members of the type, its own parameters (which may shadow outer names) and `nameof` of enclosing variables. It is emitted as a static method, so it never needs a closure, and converting it to a delegate reuses a cached delegate since C# 11. Removing `static` from a valid program changes nothing, so the modifier is pure intent. The style rule IDE0062 can suggest it, and `[Conditional]` and `extern` local functions must be static.

code

csharp · 22 lines
csharp
using System;
Console.WriteLine(new Pager(10).Describe(3));

class Pager(int pageSize)
{
    const int MaxPages = 100;
    static int created;
    int calls;

    public string Describe(int page)
    {
        calls++;
        return Format(page, pageSize);

        static string Format(int p, int size)
        {
            created++;                          // static member: allowed
            _ = nameof(page);                   // nameof of an enclosing parameter: allowed
            return $"page {p} of {MaxPages}, size {size}, calls {calls}, page {page}";
        }
    }
}

go deeper

for a junior

Recall that static on a local function, since C# 8, means it cannot use the enclosing method's locals, parameters or this.

for a middle

Explain the two errors, CS8421 for locals and parameters and CS8422 for this and instance members, and what remains allowed: constants, statics and nameof.

for a senior

Use static in review to lock in no-capture helpers on hot paths, and know it removes closures but not allocations inside the body.

for a principal

Decide whether to enforce IDE0062 team-wide: it costs little, documents data flow and prevents regressions, at the price of extra parameters in some helpers.

## What the modifier means A **static local function** is a local function declared with the `static` modifier, available since **C# 8**. The modifier does not mean "shared between calls" the way a static field is shared; it means the function **cannot capture state** from its enclosing scope. Everything it needs comes in through its own parameters or from static and constant sources. ## What the compiler rejects The rules come from the C# 8 design and are enforced with two errors: | Reference inside the static local function | Diagnostic | |---|---| | an enclosing local or parameter, including a primary constructor parameter | **CS8421**, "A static local function cannot contain a reference to 'page'." | | `this`, `base`, or an instance field, property or method, explicit or implicit | **CS8422**, "A static local function cannot contain a reference to 'this' or 'base'." | An implicit instance reference counts: writing `calls++` for an instance field, or calling `ToString()` without a receiver, is CS8422 just like writing `this.calls++`. ## What it may still use - `const` declarations, both local constants of the enclosing method and constants of the type; - **static members** of the enclosing type and of any other type; - its **own parameters and locals**, which may shadow enclosing names (allowed since C# 8); - `nameof` of enclosing locals, parameters, `this` or `base`, since `nameof` reads only a name; - `private` static members, under the same accessibility rules as any other code in the type. A non-static local function or lambda nested inside a static one may capture the static function's own locals, but nothing outside it. ## Why reviewers ask for it 1. **No accidental capture.** A helper that was meant to be pure cannot silently start reading an outer variable after a later edit; the build fails instead. 2. **No closure, ever.** Since there is nothing to capture, there is no closure environment to allocate. Converted to a delegate, it allocates the delegate once; since C# 11 the compiler caches method group conversions of static methods. 3. **Readable data flow.** Every input is a parameter, so a reader sees exactly what the helper depends on. 4. **Required by some attributes.** A local function with `[Conditional("DEBUG")]` must be static (CS8783), and an `extern` local function (C# 9) must be static. The style rule **IDE0062**, "Make local function static", flags local functions that capture nothing so a team can enforce the habit. ## What it does not change - **Meaning.** The C# 8 design states that removing `static` from a local function in a valid program does not change the program's meaning, and that overload resolution inside the function is unaffected by the modifier. It only adds a restriction. - **Scope.** A static local function is still visible only in its enclosing block, and can still be called before its declaration. - **Allocations inside its body.** It can still create objects, box values, or, as an iterator, allocate its enumerator object. `static` removes the closure, not every allocation. - **Emission.** It is emitted as a `static` method of the containing type, even when it is only used as a delegate, and calls to it are direct calls. ## Common review comments - "This helper reads nothing from outside; make it `static`." The cheapest form of the rule, and the one IDE0062 automates. - "This static helper now needs `limit`; pass it as a parameter rather than dropping `static`." Keeps the data flow explicit. - "Dropping `static` here is fine": when the helper really is part of the method's state, such as an accumulator it updates, capturing is the honest design. ## A worked repair A paging helper inside an instance method reads an enclosing parameter and an instance field: ```csharp static string Format(int p, int size) { created++; // static field: allowed _ = nameof(page); // nameof: allowed return $"page {p}, calls {calls}, page {page}"; // CS8422, CS8421 } ``` The fix is to pass `calls` and `page` as parameters, or to drop `static` if capturing them is really intended. Either way the decision is now visible in the code.

  • Does a C# static local function guarantee that calling it allocates nothing?
    It guarantees there is no closure for captures, because it cannot capture. Its body can still allocate (new objects, boxing, string building), a static local iterator still allocates its enumerator object, and converting it to a delegate allocates the delegate once before the compiler's cache reuses it.
  • Which C# attributes and modifiers require a local function to be static?
    A local function marked `[Conditional]` must be static; otherwise the SDK reports CS8783, "Local function 'Trace(string)' must be 'static' in order to use the Conditional attribute". An `extern` local function, allowed since C# 9, must also be static, since it has no body that could use captured state.

  • A static local function keeps its local variables between calls.
  • A static local function cannot read static fields of the enclosing class.
  • nameof of an enclosing parameter is forbidden inside a static local function.
  • Adding static can change which overload a call inside the function binds to.
  • static guarantees the helper allocates nothing at all, whatever its body does.