C# Reference ยท Classes and Object-Oriented Concepts
Anonymous and local functions in C#
Reference for C# anonymous methods, lambdas and local functions: syntax, closures and captured variables, static functions, allocation costs and when to pick each.
C# has three ways to write a function without giving it a class-level name. A lambda (x => x * 2) is the modern form. An anonymous method (delegate (int x) { return x * 2; }) is the older form from C# 2. A local function is a named function declared inside another method, and it can be called, recursed into and used as a delegate.
All three can capture variables from the surrounding method. The compiler then moves those variables into a hidden object (a closure), so the function sees later changes to them and keeps them alive for as long as the function is reachable.
int factor = 3; Func<int, int> times = x => x * factor;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
Func<int, int> a = x => x + 1; // expression lambda Func<int, int, int> b = (x, y) => { return x + y; }; // statement lambda Func<int> c = static () => 42; // static lambda (no capture) var d = int (string s) => s.Length; // explicit return type Action<int> e = delegate (int n) { }; // anonymous method var f = (int x = 5) => x; // default parameter (C# 12) int Local(int x) => x * 2; // local function static int StaticLocal(int x) => x * 2; // cannot capture
| Form | Description |
|---|---|
| Lambda | parameters => body. Converts to a delegate or an expression tree (Expression<Func<...>>). Has a natural type (Func/Action) when parameter types are explicit. |
| Anonymous method | delegate (params) { body }; parameters can be omitted when unused. Cannot become an expression tree. |
| Local function | A named method inside a method; may be static, async, an iterator, generic, or have attributes. |
static modifier |
On lambdas and local functions, forbids capturing locals or this. |
Errors: CS8820 ("A static anonymous function cannot contain a reference to 'outer'") for a static lambda and CS8421 ("A static local function cannot contain a reference to 'outer'") for a static local function that uses an outer local.
Usage notes
- Captured variables live on the heap. A capturing lambda allocates a closure object, and each creation of the delegate may allocate. A
staticlambda is cached and allocates once. - Loop variables.
foreachvariables are fresh per iteration (since C# 5);forvariables are shared across iterations, the classic bug in the second example. - Local function vs. lambda. Local functions cannot be forgotten as unnamed delegates, can be recursive without tricks, avoid delegate allocation when called directly, and support
yieldandasync. Lambdas are the choice for passing inline callbacks. - Validation with iterators. Put argument checks in the outer method and the
yieldbody in a local function, so exceptions happen at the call, not at the firstMoveNext(). - Discards. Use
_for unused lambda parameters:(_, e) => ...; from C# 9 several_are allowed. - Memory leaks. A long-lived delegate (an event handler) that captures
thiskeeps the whole object alive. - Natural type and inference (C# 10):
var f = (int x) => x;works;var f = x => x;does not (error CS8917, "The delegate type could not be inferred").