What is a local function in C#, and how is it different from a lambda?
Quick Answer
A local function is a named method declared inside another method, visible only there — useful for a small helper (especially a recursive one) that doesn't belong in the class's public surface. Unlike a lambda assigned to a delegate, a local function marked static can't capture outer variables and avoids the closure allocation.
A local function is just a method defined inside another method, only callable from there. The main reason I reach for one over a lambda is when I need private, self-contained recursion — a recursive local function reads naturally, whereas a recursive lambda needs an awkward trick to reference itself. Marking it static stops it from capturing anything from the enclosing method, so the compiler won't allocate a closure object for it, which matters in a hot path. Otherwise a non-static local function behaves like a lambda — it can see and capture the outer method's locals. I use them for small one-off helpers, like a validation check, that don't deserve to be a private method on the class.
- Syntax:
int Fib(int n) => n <= 1 ? n : Fib(n - 1) + Fib(n - 2);declared inside another method — recursion reads naturally, unlike a recursive lambda which needs an awkward workaround. - Non-static local functions can capture outer locals just like a lambda, with the same closure allocation cost.
- Definite-assignment analysis is smarter for local functions than lambdas — the compiler can see they're only called after a variable is set.
- Good for validation/guard helpers used once, right where they're used, without polluting the class.