In C#, what is a local function, and how does it differ from a private helper method declared on the class?
answer
- a method nested inside a member
- callable only from its container
- no access modifier allowed
- sees enclosing locals and parameters
- callable above its own declaration
basics
~20 sA local function is a named method declared inside another member. Only that member can call it, it takes no access modifier, it can use the member's locals and parameters, and it can be called before its declaration.
solid answer
~50 sA local function (C# 7) is a method declared as a statement inside a method, constructor, accessor, lambda or another local function. Unlike a `private` method on the class, nothing else in the type can call it, so the helper's scope matches its one caller. It takes no access modifier (writing `private` breaks the build), but it can be `static`, `async`, `unsafe` or `extern`, generic, and an iterator. A non-static local function reads and writes the enclosing member's locals and parameters directly instead of taking them as arguments. Because it is a declaration rather than a variable holding a delegate, it is in scope across its whole block, so it can be called from a line above it. The compiler emits it as a method with a generated name, and warns with CS8321 when one is never used.
code
csharp · 24 linesusing System;
using System.Collections.Generic;
var tree = new Dir("root", [new Dir("src", [new Dir("lib", [])]), new Dir("docs", [])]);
foreach (var path in Scanner.ListPaths(tree)) Console.WriteLine(path);
record Dir(string Name, List<Dir> Children);
static class Scanner
{
public static List<string> ListPaths(Dir root)
{
var found = new List<string>();
Walk(root, root.Name); // called before the declaration below
return found;
void Walk(Dir dir, string prefix)
{
found.Add(prefix);
foreach (var child in dir.Children)
Walk(child, $"{prefix}/{child.Name}");
}
}
}go deeper
Recall that a local function is a method declared inside another member, callable only there, with no access modifier, and able to use the enclosing locals.
Explain scope: it is in scope across its whole block, so it can be called before its declaration, and it captures enclosing variables unless marked static.
Show when you reach for one in review: a helper used by exactly one method, a recursive walk, or an iterator body, kept out of the type's member list.
Weigh readability in a coding standard: local functions keep helpers private to one algorithm, but long methods full of nested helpers can hide what a class really does.
## What a local function is A **local function** is a named method written as a statement inside another member. C# 7 introduced it for the common case of a helper that only one method needs: a recursive tree walk, a formatting step, the body of an iterator. Before local functions, such a helper had to be a `private` method on the class, visible to every other member of the type and easy to call by mistake. ```csharp public static List<string> ListPaths(Dir root) { var found = new List<string>(); Walk(root, root.Name); // called above its declaration return found; void Walk(Dir dir, string prefix) { found.Add(prefix); // uses the enclosing local foreach (var child in dir.Children) Walk(child, $"{prefix}/{child.Name}"); } } ``` ## Where you can declare one The C# documentation lists the members that can contain local functions: - methods, including iterator and async methods; - constructors, property accessors, event accessors and finalizers; - lambda expressions and anonymous methods; - other local functions. An expression-bodied member cannot contain one, because it has no block to hold the declaration statement. Methods written among **top-level statements** are local functions too: they belong to the generated entry point, which is why `public static void Helper()` there fails with CS0106, "The modifier 'public' is not valid for this item". ## What a local function can see A non-static local function can use everything in scope at its declaration: - the enclosing member's **parameters** and **locals**, read and written directly (they become captured variables); - `this` and the instance members of the type, when the enclosing member is an instance member; - type parameters of the enclosing method. Its own parameters may reuse an enclosing local's name since C# 8 (shadowing). Marking it `static` (C# 8) removes access to enclosing locals, parameters and `this`, and the compiler then rejects any reference to them. ## Compared with a private method | | Local function | `private` method | |---|---|---| | Who can call it | only the containing member | any member of the type | | Access modifier | none allowed | optional, defaults to `private` | | Enclosing locals and parameters | captured directly | must be passed as arguments | | Declared where | anywhere in the block, even after the call | among the type's members | | Unused | warning CS8321 | no warning from the compiler by default | The local function keeps a helper next to its only caller, and the compiler enforces that nobody else calls it. ## Modifiers and what the compiler rejects 1. Allowed modifiers: `static`, `async`, `unsafe` and `extern` (C# 9, and an `extern` local function must also be `static`). 2. Access modifiers such as `private` or `public` are rejected. Inside a class method the parser reads `private` as the start of a new class member and reports CS1513, "} expected"; among top-level statements the SDK reports CS0106. 3. Generic type parameters, constraints, `ref`, `out` and `params` parameters and default values all work as on any method. 4. Attributes on the function, its parameters and its type parameters are allowed since C# 9. ## What the compiler emits A local function usually becomes a method of the containing type with a compiler-generated name such as `<ListPaths>g__Walk|0_0` (or a method of a generated closure class when its captures must live on the heap). When it captures locals, the compiler adds a hidden parameter that carries them, usually a struct passed by reference, so a local function that is only called allocates nothing for its captures. When it is converted to a delegate, it behaves like a lambda and its captures move to a heap object. Calls to it are direct method calls, never virtual ones. ## When to choose one - A helper used by **exactly one** method, especially when it needs several of that method's locals: a local function avoids long parameter lists. - A **recursive** step such as a directory walk, which a lambda cannot express without a helper variable. - The **body of an iterator or async method** whose arguments the outer method validates first. - Prefer a `private` method instead when two members need the helper, or when the enclosing method is already long enough that nesting would hide its structure. Local functions are about **scope and intent** first: the helper is part of one algorithm, so it lives inside that algorithm. Everything else (capture, recursion, eager iterator validation) follows from it being a real method with a name.
- Why does public static void Helper() written among C# top-level statements fail to compile?Methods written among top-level statements are local functions of the generated entry point, not members of a `Program` class. Local functions take no access modifier, so the SDK reports CS0106, "The modifier 'public' is not valid for this item". Drop the modifier, or move the method into a type declared after the statements if it must be a real member.
- Can a C# local function's parameter reuse the name of a local in the enclosing method?Yes, since C# 8 a local function's parameters and locals may shadow the enclosing member's locals and parameters; earlier versions rejected it. Shadowing is common with a `static` local function, which takes the values it needs as parameters and often gives them the same names as the outer variables.
- Adding private to a local function is harmless and documents intent.
- A local function must be declared above the first line that calls it.
- A local function cannot read the enclosing method's parameters.
- Other methods of the same class can call a local function by name.
- A local function is just a named lambda and always allocates a delegate.