ZetCode

C# lambda expression

last modified November 15, 2026

This tutorial shows how to write and use lambda expressions in C#. We cover expression and statement lambdas, natural delegate types, default and params parameters, closures, static lambdas, expression trees, and parameter modifiers on simple lambdas.

A lambda expression is an anonymous function: a function without a name, written inline where it is needed. A lambda can be assigned to a delegate, such as Func or Action, passed as an argument, or converted to an expression tree. Lambdas are used in LINQ queries, as event handlers, as callbacks, and as custom comparers.

A lambda has one of two forms:

Syntax Description
(parameters) => expression Expression lambda; its body is a single expression whose value is returned.
(parameters) => { statements } Statement lambda; its body is a block that uses return to return a value.

The parentheses are optional when there is exactly one parameter without an explicit type: x => x * x. A lambda without parameters is written with empty parentheses: () => 42.

Expression lambdas

The following example defines four simple functions with expression lambdas.

Program.cs
Func<int, int> square = x => x * x;
Func<int, int> cube = x => x * x * x;
Func<int, int, int> add = (x, y) => x + y;
Func<int, bool> isEven = x => x % 2 == 0;

Console.WriteLine(square(5));
Console.WriteLine(cube(5));
Console.WriteLine(add(5, 7));
Console.WriteLine(isEven(5));

Each lambda is assigned to a Func delegate. The last type argument of Func is the return type; the preceding ones are the parameter types.

Func<int, int> square = x => x * x;

The lambda takes an integer and returns its square. The type of x is inferred from the delegate type.

Func<int, int, int> add = (x, y) => x + y;

A lambda with two or more parameters needs parentheses around them.

Func<int, bool> isEven = x => x % 2 == 0;

A lambda that returns bool is often called a predicate.

$ dotnet run
25
125
12
False

Statement lambdas

A statement lambda has a block body enclosed in {} braces. It can contain any number of statements.

Program.cs
Action<string> greet = name =>
{
    string greeting = $"Hello {name}!";
    Console.WriteLine(greeting);
};

greet("Paul");
greet("Lucia");

Func<int, string> classify = n =>
{
    if (n < 0)
    {
        return "negative";
    }

    return n == 0 ? "zero" : "positive";
};

Console.WriteLine(classify(-4));
Console.WriteLine(classify(0));

We define a lambda that returns nothing and one that returns a string.

Action<string> greet = name =>
{
    string greeting = $"Hello {name}!";
    Console.WriteLine(greeting);
};

An Action delegate takes parameters but returns no value. The lambda builds a greeting and prints it.

Func<int, string> classify = n =>
{
    if (n < 0)
    {
        return "negative";
    }

A statement lambda that produces a value uses the return statement, just like a method. Every code path must return a value.

$ dotnet run
Hello Paul!
Hello Lucia!
negative
zero

Natural type of lambdas

Since C# 10, a lambda has a natural type when the compiler can infer the types of its parameters and its return value. Such a lambda can be assigned to a var variable.

Program.cs
var square = (int x) => x * x;
var greet = () => Console.WriteLine("Hello!");
var parse = object (string s) => int.TryParse(s, out int n) ? n : s;

Console.WriteLine(square.GetType());
Console.WriteLine(greet.GetType());
Console.WriteLine(parse.GetType());

Console.WriteLine(square(6));
greet();
Console.WriteLine(parse("42").GetType());
Console.WriteLine(parse("forty").GetType());

The compiler chooses a Func or Action delegate for each lambda.

var square = (int x) => x * x;

The parameter type must be written explicitly; the return type is inferred from the body. The natural type is Func<int, int>.

var parse = object (string s) => int.TryParse(s, out int n) ? n : s;

The two branches of the conditional have different types, so the return type cannot be inferred. We specify it in front of the parameter list.

$ dotnet run
System.Func`2[System.Int32,System.Int32]
System.Action
System.Func`2[System.String,System.Object]
36
Hello!
System.Int32
System.String

Default and params parameters

Since C# 12, lambda parameters can have default values, and the last parameter can be a params array. No Func or Action type can describe such parameters, so the compiler synthesizes an anonymous delegate type (named, for instance, <>f__AnonymousDelegate0`3).

Program.cs
var message = (string greet, string name = "there") => $"{greet} {name}!";

Console.WriteLine(message("Hi", "Tom"));
Console.WriteLine(message("Hello"));

var sum = (params int[] vals) => vals.Sum();

Console.WriteLine(sum());
Console.WriteLine(sum(1, 2, 3, 4));

The first lambda has an optional parameter, the second a params array.

var message = (string greet, string name = "there") => $"{greet} {name}!";

The name parameter is optional. Optional parameters must follow the required ones.

var sum = (params int[] vals) => vals.Sum();

The lambda accepts any number of integers, including none.

$ dotnet run
Hi Tom!
Hello there!
0
10

Lambdas with arrays

Several static methods of the Array class take a predicate, which is tested on the elements of the array.

Program.cs
int[] vals = [1, -2, 3, 4, 0, -3, 2, 1, 3];

int first = Array.FindIndex(vals, x => x == 3);
Console.WriteLine(first);

int last = Array.FindLastIndex(vals, x => x == 3);
Console.WriteLine(last);

int[] positive = Array.FindAll(vals, x => x > 0);
Console.WriteLine(string.Join(",", positive));

bool allSmall = Array.TrueForAll(vals, x => Math.Abs(x) < 5);
Console.WriteLine(allSmall);

We search and filter an array of integers.

int first = Array.FindIndex(vals, x => x == 3);

FindIndex returns the index of the first element that satisfies the predicate, or -1. FindLastIndex searches from the end.

int[] positive = Array.FindAll(vals, x => x > 0);

FindAll returns a new array with all elements for which the predicate returns true.

bool allSmall = Array.TrueForAll(vals, x => Math.Abs(x) < 5);

TrueForAll checks whether every element satisfies the predicate.

$ dotnet run
2
8
1,3,4,2,1,3
True

Lambdas with LINQ

LINQ methods take lambdas for projections, filters, keys, and aggregations.

Program.cs
List<int> vals = [-1, 2, -2, 0, 3, 4, -5];

var squared = vals.Select(x => x * x);
Console.WriteLine(string.Join(", ", squared));

var filtered = vals.Where(x => x > 0);
Console.WriteLine(string.Join(", ", filtered));

var indexed = vals.Where((x, i) => i % 2 == 0);
Console.WriteLine(string.Join(", ", indexed));

int negatives = vals.Count(x => x < 0);
Console.WriteLine(negatives);

We transform, filter, and count the values of a list.

var squared = vals.Select(x => x * x);

Select applies the lambda to each element.

var indexed = vals.Where((x, i) => i % 2 == 0);

An overload of Where also passes the index of the element. The lambda keeps the elements at even positions.

$ dotnet run
1, 4, 4, 0, 9, 16, 25
2, 3, 4
-1, -2, 3, -5
3

Collections of lambdas

Lambdas are values, so they can be stored in collections.

Program.cs
Dictionary<string, Func<double, double, double>> ops = new()
{
    ["+"] = (a, b) => a + b,
    ["-"] = (a, b) => a - b,
    ["*"] = (a, b) => a * b,
    ["/"] = (a, b) => a / b
};

foreach (var (symbol, op) in ops)
{
    Console.WriteLine($"12 {symbol} 4 = {op(12, 4)}");
}

Func<int, int>[] steps =
[
    x => x + 1,
    x => x * 10,
    x => x - 3
];

int value = 2;

foreach (var step in steps)
{
    value = step(value);
}

Console.WriteLine(value);

We create a table of arithmetic operations and a pipeline of steps.

Dictionary<string, Func<double, double, double>> ops = new()
{
    ["+"] = (a, b) => a + b,

The dictionary maps an operator symbol to a lambda that performs the operation. Such a table replaces a long switch statement.

foreach (var step in steps)
{
    value = step(value);
}

The steps are applied one after another: (2 + 1) * 10 - 3 = 27.

$ dotnet run
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3
27

Discard parameters

Since C# 9, unused lambda parameters can be named _. This is common in event handlers, which receive a sender and event arguments that are often not needed.

Program.cs
Func<int, int, int> answer = (_, _) => 42;
Console.WriteLine(answer(3, 4));

AppDomain.CurrentDomain.ProcessExit += (_, _) => Console.WriteLine("exiting");

Console.WriteLine("main work done");

The example ignores the parameters of two lambdas.

Func<int, int, int> answer = (_, _) => 42;

With two or more parameters named _, they are discards; we cannot read them in the body.

AppDomain.CurrentDomain.ProcessExit += (_, _) => Console.WriteLine("exiting");

The ProcessExit event is raised when the process is about to exit. The handler does not use its sender and EventArgs parameters.

$ dotnet run
42
main work done
exiting

Closures and static lambdas

A lambda can use variables of its enclosing scope. It captures the variables themselves, not copies of their values; this is called a closure.

Program.cs
int factor = 3;
Func<int, int> multiply = x => x * factor;

Console.WriteLine(multiply(5));

factor = 4;
Console.WriteLine(multiply(5));

var counters = new List<Func<int>>();

for (int i = 0; i < 3; i++)
{
    counters.Add(() => i);
}

Console.WriteLine(string.Join(" ", counters.Select(f => f())));

Func<int, int> twice = static x => x * 2;
Console.WriteLine(twice(21));

We show the effect of capturing and how to prevent it.

factor = 4;
Console.WriteLine(multiply(5));

The lambda reads the current value of factor each time it is called, so the change is visible.

for (int i = 0; i < 3; i++)
{
    counters.Add(() => i);
}

A for loop has a single i variable that all three lambdas share. They are called after the loop has finished, when i is 3. (A foreach loop creates a new variable in each iteration, so it does not have this problem.)

Func<int, int> twice = static x => x * 2;

The static modifier, available since C# 9, forbids capturing. Using an outer variable in a static lambda is an error (CS8820). Static lambdas avoid accidental captures and the allocations that come with them.

$ dotnet run
15
20
3 3 3
42

Lambdas as comparers

The List.Sort method accepts a Comparison<T> delegate. The lambda returns a negative number, zero, or a positive number when the first element is smaller than, equal to, or greater than the second.

Program.cs
List<string> words = ["pear", "fig", "apple", "kiwi", "banana", "plum"];

words.Sort((a, b) => a.Length.CompareTo(b.Length));
Console.WriteLine(string.Join(", ", words));

words.Sort((a, b) =>
{
    int c = a.Length.CompareTo(b.Length);
    return c != 0 ? c : string.CompareOrdinal(a, b);
});

Console.WriteLine(string.Join(", ", words));

var byLength = words.OrderByDescending(w => w.Length).ThenBy(w => w);
Console.WriteLine(string.Join(", ", byLength));

We sort words by their length.

words.Sort((a, b) => a.Length.CompareTo(b.Length));

The words are sorted by length. List.Sort is not stable, so the order of words with the same length is not guaranteed.

int c = a.Length.CompareTo(b.Length);
return c != 0 ? c : string.CompareOrdinal(a, b);

The second comparer breaks ties alphabetically, which makes the order fully defined.

var byLength = words.OrderByDescending(w => w.Length).ThenBy(w => w);

With LINQ, the lambdas only select the sort keys. OrderBy and ThenBy are stable.

$ dotnet run
fig, pear, kiwi, plum, apple, banana
fig, kiwi, pear, plum, apple, banana
banana, apple, kiwi, pear, plum, fig

Expression trees

A lambda assigned to Expression<TDelegate> is not compiled to code. The compiler builds an expression tree, a data structure that describes the lambda. Libraries such as Entity Framework Core translate expression trees to SQL.

Program.cs
using System.Linq.Expressions;

Func<int, int> f = x => x * x + 1;
Expression<Func<int, int>> e = x => x * x + 1;

Console.WriteLine(f(3));
Console.WriteLine(e);
Console.WriteLine(e.Body.NodeType);
Console.WriteLine(e.Parameters[0].Name);

Func<int, int> compiled = e.Compile();
Console.WriteLine(compiled(3));

The same lambda is compiled to a delegate and to an expression tree.

Expression<Func<int, int>> e = x => x * x + 1;

The variable holds a tree of nodes. Its ToString method prints the expression, and we can inspect the body and the parameters.

Func<int, int> compiled = e.Compile();

The Compile method turns the tree into an executable delegate. Only expression lambdas can be converted to expression trees, not statement lambdas.

$ dotnet run
10
x => ((x * x) + 1)
Add
x
10

Parameter modifiers on simple lambdas

Lambda parameters can have the ref, out, in, and scoped modifiers. Before C# 14, using a modifier required writing the types of all parameters. Since C# 14, the types can be left out and are inferred from the delegate.

Program.cs
TryParse<int> parse = (text, out result) => int.TryParse(text, out result);

if (parse("123", out int n))
{
    Console.WriteLine(n + 1);
}

Console.WriteLine(parse("abc", out _));

Increment inc = (ref x) => x++;

int count = 5;
inc(ref count);
inc(ref count);

Console.WriteLine(count);

delegate bool TryParse<T>(string text, out T result);
delegate void Increment(ref int value);

We create lambdas with out and ref parameters for two custom delegate types.

TryParse<int> parse = (text, out result) => int.TryParse(text, out result);

The types of text and result come from the TryParse<int> delegate. In C# 13, the lambda would have to be written as (string text, out int result) => ....

Increment inc = (ref x) => x++;

The lambda increments the variable passed by reference. After two calls, count is 7.

$ dotnet run
124
False
7

Source

Lambda expressions and anonymous functions

Expression trees

In this article we have worked with lambda expressions in C#. See also the delegate, Func, Predicate, and closure tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.