Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Statement Lambda: Syntax and Practical Usage

Learn C# statement lambdas, their syntax, how they differ from expression lambdas, and when to use them in delegates, LINQ, and async code.

~5 min readC#
#C##lambda expressions#delegates#LINQ
Diagram showing a C# statement lambda with a block body and multiple statements.

A statement lambda in C# is a lambda expression that uses a block body. Unlike an expression lambda, which evaluates to a single expression, a statement lambda can contain multiple statements, making it suitable for more complex logic that cannot be expressed as a single expression. The syntax is simple: optional parameters, the => operator, and a block enclosed in braces.

csharp
// Expression lambda Func<int, int> square = x => x * x; // Statement lambda Func<int, int> squareWithLog = x => { Console.WriteLine($"Squaring {x}"); return x * x; };

The statement lambda above writes a message and returns the square. That is the core difference: the block body allows arbitrary statements, but it also requires an explicit return statement when the delegate expects a return value.

Statement Lambda Syntax and Structure

The general shape of a statement lambda is:

csharp
(parameters) => { // statements // optional return }

The parameter list follows the same rules as expression lambdas. You can omit parentheses for a single parameter, but the braces are still required. The block can contain any valid C# statements: variable declarations, if blocks, for loops, try-catch blocks, and so on.

Here is a more involved example that uses a statement lambda to filter a list:

csharp
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; var evens = numbers.Where(n => { bool isEven = n % 2 == 0; if (isEven) { Console.WriteLine($"{n} is even"); } return isEven; }).ToList();

The lambda does more than filter; it also logs each even number. Where expects a Func<int, bool>, and the statement lambda provides that by returning a boolean.

When to Use a Statement Lambda vs an Expression Lambda

The choice between a statement lambda and an expression lambda is mainly about readability and complexity. An expression lambda is more concise and is required when you need to build an expression tree, such as in Entity Framework's IQueryable APIs. Statement lambdas cannot be converted to expression trees, so they cannot be used where an Expression<TDelegate> parameter is expected. Passing one causes a compile-time error.

Use a statement lambda when:

  • The logic requires more than a single expression, such as multiple statements or a switch statement.
  • You need to declare intermediate variables to make the code clearer.
  • You are working with delegates like Func or Action that do not require expression trees.

Use an expression lambda when:

  • The body is a simple expression that can be written in one line.
  • You need to pass the lambda to a method that expects an expression tree, like Entity Framework or other IQueryable providers.
  • You want to keep the code as short as possible.

The rule of thumb is: if you can write it as an expression lambda, prefer it. If you need more than one statement, switch to a statement lambda.

The following table summarizes the key differences:

FeatureExpression LambdaStatement Lambda
BodySingle expressionBlock of statements
ReturnImplicitExplicit return
Expression tree conversionPossible for non-async expression lambdasNot supported
Use casesSimple logic, query providers needing expression treesComplex logic, multiple statements

Practical Examples: Statement Lambdas with Delegates and LINQ

Statement lambdas are commonly used with delegates like Func and Action. They are also useful in event handlers and asynchronous code.

Using Statement Lambdas with Func and Action

Func delegates return a value, while Action delegates return void. A statement lambda can be assigned to either.

csharp
Func<int, int, int> add = (a, b) => { int sum = a + b; Console.WriteLine($"Adding {a} and {b}"); return sum; }; Action<string> greet = name => { string message = $"Hello, {name}!"; Console.WriteLine(message); };

The add lambda uses a local variable and a Console.WriteLine call before returning. The greet lambda does not return anything, so it does not need a return statement.

Statement Lambdas in LINQ

LINQ methods like Where, Select, and Aggregate accept delegates. For in-memory collections (IEnumerable<T>), you can use statement lambdas freely. For IQueryable<T>, you must use expression lambdas instead.

csharp
var doubled = numbers.Select(n => { int result = n * 2; return result; }).ToList();

This is unnecessarily verbose for such a simple operation, but it demonstrates that the syntax is valid. Use statement lambdas in LINQ when the transformation requires more than a single expression.

Common Mistakes and Pitfalls with Statement Lambdas

A few mistakes are easy to make when writing statement lambdas.

Forgetting the Return Statement

If a delegate expects a return value, the statement lambda must have an explicit return statement. Missing it results in a compile-time error. For example:

csharp
Func<int, int> bad = x => { Console.WriteLine(x); // Error: not all code paths return a value };

The compiler requires that every code path returns a value. This is a common source of errors for developers new to statement lambdas.

Using Statement Lambdas Where Expression Trees Are Required

Statement lambdas cannot be converted to expression trees. The following assignment fails to compile:

csharp
Expression<Func<int, bool>> predicate = n => { return n > 5; }; // Error: cannot convert statement lambda to expression tree

If you need to build an expression tree, you must use an expression lambda.

Scope and Variable Capture

Statement lambdas capture variables from the enclosing scope just like expression lambdas. Because they contain more code, it can be easier to accidentally modify a captured variable in ways that are hard to reason about. The same closure rules apply as with expression lambdas.

Performance and Maintainability Considerations

With delegates, statement lambdas do not have a distinct performance cost relative to expression lambdas; the compiler still creates a delegate instance and, if variables are captured, a closure object. As with any lambda in a hot path, repeated allocations can matter, but this is not specific to statement lambdas.

From a maintainability perspective, statement lambdas can be harder to read because they contain more logic. If a lambda grows beyond a few statements, consider extracting it into a named method. This improves readability and testability. For example, instead of a long statement lambda in a LINQ query, define a private method and pass a method group.

csharp
private static bool IsEvenAndPositive(int n) { return n % 2 == 0 && n > 0; } // Usage var result = numbers.Where(IsEvenAndPositive).ToList();

This is often clearer than a multi-line statement lambda.

Statement Lambdas with Async and Await

Statement lambdas are particularly useful when you need to use await inside a lambda. Expression lambdas can also be async, but if you have multiple awaits or other statements, a statement lambda is the natural choice.

csharp
Func<Task<int>> getValue = async () => { await Task.Delay(100); int value = 42; return value; };

You can also use async statement lambdas as event handlers:

csharp
button.Click += async (sender, e) => { await LoadDataAsync(); UpdateUI(); };

The async keyword is placed before the parameter list. When the target delegate expects a Task or Task<T>, the compiler generates the returned task for you. When the target delegate returns void, as with EventHandler, the lambda behaves like an async void method, so it is best to handle exceptions inside the handler.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.