skip to content

In C#, why does a recursive lambda assigned to a Func or Action variable fail with CS0165, while a recursive local function compiles?

level: middleimportance: should knowfreq 48%

answer

  1. definite assignment of the delegate variable
  2. initializer reads what it assigns
  3. a declaration, not a value
  4. null-first workaround and its cost

basics

~20 s

The lambda's body reads the delegate variable inside that variable's own initializer, before it is definitely assigned, so the compiler reports CS0165. A local function is a named method in scope across its block, so it can call itself directly.

solid answer

~50 s

In `Action<Dir, string> walk = (dir, prefix) => { ... walk(child, ...); };` the lambda body reads `walk`, and C#'s definite assignment rules say `walk` is not assigned until the whole initializer finishes, so the compiler reports CS0165, "Use of unassigned local variable 'walk'". With `var` and a lambda's natural type (C# 10) the error is CS0841 instead. The old workaround declares the variable as `null` first and assigns the lambda second: it compiles, but it allocates a closure and a delegate, and the recursion calls whatever the variable holds at run time. A local function is a method declaration, not a variable, so it is in scope across its whole block and can call itself with no assignment step. It can also be generic and can be an iterator with `yield return`, which a lambda cannot.

code

csharp · 15 lines
csharp
using System;
using System.Collections.Generic;

var found = new List<string>();
var root = new Dir("root", [new Dir("src", [])]);
Action<Dir, string> walk = (dir, prefix) =>
{
    found.Add(prefix);
    foreach (var child in dir.Children)
        walk(child, $"{prefix}/{child.Name}");
};
walk(root, root.Name);
Console.WriteLine(string.Join(", ", found));

record Dir(string Name, List<Dir> Children);

go deeper

for a junior

Recall that a local function can call itself directly, while a lambda in a Func or Action variable cannot reference that variable in its own initializer.

for a middle

Explain the definite assignment rule behind CS0165, why var gives CS0841 instead, and what the null-first workaround costs in allocations and safety.

for a senior

In review, replace recursive delegate variables with local functions, mark them static when they need no outer state, and convert to a delegate only where an API demands one.

for a principal

Treat it as a style-guide point: the analyzer rule that suggests local functions over lambdas is worth enabling, since it removes a class of allocation and reassignment bugs.

## The failing lambda A file-system scanner wants a recursive `walk` helper. Written as a lambda stored in a delegate variable, it does not compile: ```csharp Action<Dir, string> walk = (dir, prefix) => { found.Add(prefix); foreach (var child in dir.Children) walk(child, $"{prefix}/{child.Name}"); // CS0165 }; ``` The SDK reports **CS0165**, "Use of unassigned local variable 'walk'". ## Why the compiler rejects it C# requires every local variable to be **definitely assigned** before it is read. For a declaration with an initializer, the variable is assigned only when the initializer has been evaluated. The lambda body is part of that initializer, and it reads `walk`, so the compiler sees a read of a variable that is not yet assigned. The compiler does not reason that the body runs later; the rule is about the variable, and the variable is read inside its own initializer. With `var walk = (Dir dir, string prefix) => ...` (a lambda with a natural type, C# 10), the error changes to **CS0841**, "Cannot use local variable 'walk' before it is declared", because an implicitly typed local cannot be referenced in its own initializer at all. ## The null-first workaround ```csharp Action<Dir, string>? walk = null; walk = (dir, prefix) => { /* ... */ walk!(child, path); }; ``` This compiles, and it is what code written before C# 7 did. It has costs: 1. The lambda captures `walk` (and `found`), so the compiler builds a **heap closure** object and a **delegate**: an allocation on every call of the enclosing method. 2. Recursion goes through the delegate stored in a **mutable variable**. If later code reassigns `walk`, the next recursive step calls the new delegate, not the original body. 3. Nullable reference types make the null-first declaration noisy (`?` and `!`). ## Why a local function compiles A local function is a **declaration**, like a method on a class. It has a name and a signature before any code runs, and it is in scope across its whole enclosing block. A recursive call is a direct call to that method: there is no variable to assign, so definite assignment never applies to the function itself. ```csharp void Walk(Dir dir, string prefix) { found.Add(prefix); foreach (var child in dir.Children) Walk(child, $"{prefix}/{child.Name}"); } ``` Definite assignment still applies to the **variables it captures**, and the compiler tracks it through calls: if `void Set() => y = 42;` is called before `return y;`, then `y` counts as assigned there; calling a local function that reads `threshold` before `threshold` is assigned reports CS0165 at the call. ## What else a local function can do that a lambda cannot | Capability | Local function | Lambda | |---|---|---| | Call itself without a helper variable | yes | no (CS0165 or CS0841) | | Be called above its declaration | yes | no, the variable must be assigned first | | Declare its own generic type parameters | yes | no | | Use `yield return` | yes, it can be an iterator | no, CS1621 | | Avoid a delegate when only called | yes | no, a lambda is always a delegate or an expression tree | - **Generic helpers:** `static T Max<T>(T a, T b) where T : IComparable<T>` can be a local function; a lambda has no type parameter list. - **Iterators:** a local function can contain `yield return`, which is what makes it a good home for a lazily produced recursive listing. - **Static recursion:** a recursive local function that needs no outer state can be marked `static`, so it captures nothing at all. ## In practice A code reviewer who sees `Func<...> f = null; f = ...` with a recursive call can usually replace it mechanically: turn the lambda into a local function with explicit parameter and return types, delete the null-first declaration, and add `static` if the body reads no outer variables. Behaviour stays the same, the allocation disappears, and the recursion can no longer be redirected by a later assignment. Reach for a local function whenever a helper recurses. Keep lambdas for what they are good at: a short delegate passed straight to another method. Converting a recursive local function to a delegate (passing it as a method group) is still possible when an API needs one, and only then does it pay a lambda's allocation.

  • In C#, how does definite assignment treat a local variable that a local function assigns?
    The compiler analyzes the local function's body at each call site. After `int y; Set();` with `void Set() => y = 42;`, `y` is definitely assigned, so `return y;` compiles. Calling a local function that reads a captured variable before that variable is assigned reports CS0165 at the call, even though the read is inside the function.
  • Does the null-first recursive lambda still allocate if the recursion is shallow?
    Yes. Allocation does not depend on depth: the lambda captures the delegate variable, so each call of the enclosing method creates the closure object and the delegate once, before any recursion happens. A recursive local function that is only called directly allocates neither.

  • C# lambdas can never be recursive under any circumstances.
  • The recursive lambda compiles but throws NullReferenceException at run time.
  • Declaring the delegate variable with var fixes the CS0165 error.
  • A recursive local function must be declared above its first call.
  • Each recursive call of a local function creates a new delegate.