Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 182 ยท Methods

Lambda Expressions

Learn C# lambda expressions - the => syntax, Func and Action, natural types, captured variables, static lambdas, default parameters and attributes, with runnable examples.

Sometimes you need a tiny piece of behavior and giving it a full named method feels heavy: "sort by length", "keep the even numbers", "run this when the button is clicked". A lambda expression is an unnamed method you write inline, right where you need it, and often pass to another method. Lambdas are everywhere in modern C#: LINQ queries, event handlers, List<T>.Sort, minimal web APIs, tests and async code.

This lesson explains the syntax step by step, the delegate types (Func, Action, Predicate) that lambdas are stored in, how the compiler infers types, how lambdas capture variables from the code around them (and the traps that come with it), and the newer features: static lambdas, default parameter values, params, and attributes.

The syntax: parameters => body

A lambda has parameters on the left of the => operator ("goes to") and a body on the right. If the body is a single expression, its value is the result:

C# Your first lambdas

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.

Rules for the parts:

  • One parameter without a type may skip the parentheses: x => x * x. Zero or several parameters need them: () => ..., (a, b) => ....
  • The body can be an expression (a + b) or a statement block in braces with explicit return.
  • The value of an expression body is returned automatically. For Action delegates, the expression is just evaluated and the value thrown away.

A block body is for multiple steps:

C# Expression bodies and block bodies

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.

Func, Action and Predicate

A lambda needs a delegate type to live in. You rarely declare your own; the library provides generic ones. Delegates are covered fully in Delegates, but you need three of them now:

Type Meaning Example
Action, Action<T>, ... Takes 0-16 parameters, returns nothing Action<string> log = s => Console.WriteLine(s);
Func<TResult>, Func<T, TResult>, ... Takes 0-16 parameters, last type is the return type Func<int, int, int> add = (a, b) => a + b;
Predicate<T> Takes a T, returns bool Predicate<int> isEven = n => n % 2 == 0;

The last type argument of Func is the result, so Func<string, int> takes a string and returns an int. Lambdas make methods that take behavior easy to write:

C# Passing lambdas to methods

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.

ApplyAll does not know or care what the transformation is; the caller supplies it. The compiler infers TIn from numbers and TOut from what the lambda returns (int in one call, string in the other).

Types are inferred, and lambdas have natural types

Usually the compiler figures out parameter types from the delegate type you assign to or pass the lambda into. You can still write them explicitly, which helps readability or resolves overloads:

C#
Func<int, int, int> multiply = (int a, int b) => a * b;   // explicit types

Since C# 10 many lambdas have a natural type, so var works. The compiler picks Func<...> or Action<...> based on the parameter types and body. For that to work, every parameter needs an explicit type:

C# var with lambdas (C# 10)

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.

The two GetType() lines print the real delegate types, so you can see Func and Action at work. Without types (var f = x => x * 3;) the compiler reports an error because it cannot guess x.

Captured variables (closures)

A lambda can read and modify local variables of the method around it. The lambda captures the variable itself, not a copy of its value at that moment. A lambda that has captured something is called a closure.

C# Closures see later changes

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.

The first call prints 50 and the second 500, because the lambda holds on to factor, not to the number 10. To make that possible, the compiler moves captured variables into a hidden object on the heap, which lives as long as any lambda that uses them. That is convenient, and it has a cost: capturing allocates, so do not capture in a hot loop if you can avoid it.

The loop variable trap

A for loop has one variable that changes on each pass. If lambdas capture it, they all share it:

C# Capturing a for variable vs a foreach variable

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.

All three lambdas from the for loop print 3: when they finally run, the loop has finished and i is 3. Since C# 5, a foreach variable is fresh on every pass, so that loop gives 0, 1, 2. For a for loop, copy the variable into a local declared inside the body.

static lambdas: no capture allowed

When you do not want a lambda to depend on surrounding variables (for example to avoid an allocation, or to guarantee it is pure), mark it static (C# 9). The compiler then rejects any capture:

C# static lambdas (fails on purpose)

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.

The compiler stops with error CS8820: A static anonymous function cannot contain a reference to 'offset'. The first lambda is fine because it only uses its own parameter; the second is rejected. Use static on lambdas passed to hot paths and library methods: it documents intent and may let the compiler cache a single delegate instance instead of creating a new one per call.

Modern parameter features

Lambdas gained several abilities in recent versions. They are not very common, but you will meet them in minimal APIs and library code.

  • Default parameter values (C# 12): (int x, int y = 1) => x + y.
  • params arrays (C# 12): (params int[] values) => values.Sum().
  • Modifiers without types (C# 14): (text, out result) => int.TryParse(text, out result) works without writing the parameter types.
  • Attributes on the lambda or its parameters (C# 10): [Obsolete] () => 42.
  • Explicit return type (C# 10): int (string s) => s.Length.
C# Defaults, params and return types

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.

The default value belongs to the lambda's own signature, so it works when you call increase directly. If you assign the lambda to a Func<int, int, int>, the default is lost, because Func has no concept of default values.

Lambdas versus local functions and methods

A lambda is an expression that produces a delegate. A local function is a named method declared inside another method. Prefer a local function when you need recursion, a name for readability, or generic parameters; prefer a lambda when you pass a short piece of code straight into a method call.

Lambdas that return a lambda ("function factories") are a handy way to configure behavior:

C# A function that returns a function

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.

Each call to makeMultiplier creates a separate closure with its own factor, so doubler and tenfold do not interfere.

Common pitfalls

  • Capturing loop variables in for loops. Copy to a local.
  • Large captured objects keep memory alive. A lambda stored in a long-lived event holds everything it captured.
  • Side effects in lambdas passed to LINQ. Queries may run later, more than once, or not at all.
  • Overusing complex block lambdas. If it needs ten lines, give it a name.
  • Assuming equality. Two lambdas with identical bodies are different delegate objects.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the last type argument of Func<int, string, bool> represent?

    For Func the last type argument is always the result type. Here the delegate takes an int and a string and returns bool.
  2. 2. What does this code print? int n = 1; Func<int> f = () => n; n = 5; Console.WriteLine(f());

    The lambda captures the variable n, not its value at the moment of creation, so it sees the later assignment and returns 5.
  3. 3. Why do lambdas created in a for loop body that return the loop variable i all give the same number?

    All lambdas capture the same variable. By the time they run, the loop has finished. Copy i into a local variable inside the body to give each lambda its own.
  4. 4. What does the static modifier on a lambda do?

    A static lambda is checked at compile time not to capture anything from the surrounding scope, which documents intent and avoids closure allocations.
  5. 5. Which line gives var a natural type in C# 10 and later?

    The compiler needs explicit parameter types to infer a Func or Action type for a lambda assigned to var.

Summary

  • A lambda is an inline, unnamed method: (parameters) => expression or => { statements }.
  • Store lambdas in Func (returns a value), Action (returns nothing) or Predicate<T> (returns bool).
  • Lambdas capture variables, not values; loop variables of for loops are shared, so copy them.
  • static lambdas forbid capturing and can avoid allocations.
  • Newer C# adds natural types, default parameters, params, attributes, and modifier parameters without types.
  • Use local functions when you need names, recursion, or generics.

Next: Tuples and Deconstruction