ZetCode

C# expression trees

last modified November 15, 2026

This article shows how to use expression trees in C#. We inspect a lambda as data, build an expression tree by hand, create a query filter at run time, rewrite a tree with ExpressionVisitor, and translate a predicate into SQL.

An expression tree is an object graph that represents code. The compiler can turn a lambda expression into such a graph when the target type is Expression<TDelegate> instead of a delegate type. Where Func<int, int> is executable code, Expression<Func<int, int>> is a description of that code: each node has a type, children, and a value. Because the tree is ordinary data, a program can inspect it, change it, or translate it into another language.

This is how LINQ providers work. A query written against IQueryable<T> captures the lambda as an expression tree, and the provider walks the tree to produce SQL, a REST call, or something else. The same mechanism supports dynamic filters, rule engines, and serialization of logic.

Inspecting an expression tree

A lambda assigned to Expression<TDelegate> becomes a tree. The Body property is the root expression, and Parameters holds the parameters that the body refers to. Every node derives from Expression and reports its kind through NodeType.

Program.cs
using System.Linq.Expressions;

Expression<Func<int, int, int>> expr = (a, b) => a * b + 1;

Console.WriteLine(expr);
Console.WriteLine(expr.Body.NodeType);
Console.WriteLine(expr.Parameters.Count);

var add = (BinaryExpression)expr.Body;
Console.WriteLine($"left: {add.Left}, right: {add.Right}");

var multiply = (BinaryExpression)add.Left;
Console.WriteLine($"multiply: {multiply.Left} * {multiply.Right}");

Func<int, int, int> func = expr.Compile();
Console.WriteLine(func(6, 7));

We print the whole expression, the kind of the root, the number of parameters, and the two operands of the multiplication. The tree is then compiled back into a delegate and invoked.

var add = (BinaryExpression)expr.Body;
var multiply = (BinaryExpression)add.Left;

The root of a * b + 1 is an Add node, so the multiplication is its left child. Casting Body to BinaryExpression exposes Left and Right; casting Left again exposes the operands of the multiplication.

Func<int, int, int> func = expr.Compile();

Compile turns the tree into an executable delegate. Compilation is relatively expensive, so a program that runs the same dynamic query many times should compile once and cache the delegate.

$ dotnet run
(a, b) => ((a * b) + 1)
Add
2
left: (a * b), right: 1
multiply: a * b
43

Building a tree by hand

Expression trees can also be assembled without a lambda. The static methods on Expression create nodes: Parameter creates a parameter, Multiply creates a binary operation, and Lambda wraps a body and its parameters into a typed lambda.

Program.cs
using System.Linq.Expressions;

ParameterExpression x = Expression.Parameter(typeof(int), "x");
BinaryExpression square = Expression.Multiply(x, x);
Expression<Func<int, int>> lambda =
    Expression.Lambda<Func<int, int>>(square, x);

Console.WriteLine(lambda);
Console.WriteLine(lambda.Compile()(9));

We construct the equivalent of x => x * x node by node. The parameter node is reused for both operands, which is what makes the multiplication refer to the same x.

ParameterExpression x = Expression.Parameter(typeof(int), "x");
BinaryExpression square = Expression.Multiply(x, x);

The first argument of Lambda is the body and the second is the parameter list. The generic type argument fixes the delegate signature, so the compiler can check that the body returns int and that the parameter types match. Calling Compile produces a Func<int, int> that squares its argument.

$ dotnet run
x => (x * x)
81

Building a filter at run time

The real value of expression trees appears when the shape of the code is known only at run time. A method can take a column name and a minimum value and build a predicate from them. The result is a strongly typed Expression<Func<T, bool>> that LINQ can use like any other lambda.

Program.cs
using System.Linq.Expressions;

var people = new[]
{
    new Person("Alice", 34),
    new Person("Bob", 17),
    new Person("Carol", 42),
};

var filter = BuildAgeFilter(18);
Console.WriteLine(filter);

var adults = people.Where(filter.Compile()).Select(p => p.Name);
Console.WriteLine(string.Join(", ", adults));

static Expression<Func<Person, bool>> BuildAgeFilter(int minAge)
{
    ParameterExpression person = Expression.Parameter(typeof(Person), "p");
    MemberExpression age = Expression.Property(person, nameof(Person.Age));
    ConstantExpression limit = Expression.Constant(minAge);
    BinaryExpression compare = Expression.GreaterThanOrEqual(age, limit);

    return Expression.Lambda<Func<Person, bool>>(compare, person);
}

public sealed record Person(string Name, int Age);

The helper builds p => p.Age >= 18 from a parameter, a property access, a constant, and a comparison. The caller does not write the lambda at all.

MemberExpression age = Expression.Property(person, nameof(Person.Age));
BinaryExpression compare = Expression.GreaterThanOrEqual(age, limit);

Expression.Property creates a node that reads a property from the parameter. nameof keeps the member name in sync with the class. The comparison node combines the property and the constant, and the lambda node binds the parameter. A different column name or limit produces a different tree without recompiling the program.

$ dotnet run
p => (p.Age >= 18)
Alice, Carol

Rewriting a tree with ExpressionVisitor

ExpressionVisitor walks a tree and lets a subclass replace nodes as it goes. Every Visit method returns an expression; the default implementation returns the original node when nothing changes. Overriding one method is enough to transform every node of that kind.

Program.cs
using System.Linq.Expressions;

Expression<Func<int, int>> original = n => n * 3 + 4;
var rewritten = (Expression<Func<int, int>>)new DoubleConstants().Visit(original)!;

Console.WriteLine(original);
Console.WriteLine(rewritten);
Console.WriteLine(original.Compile()(2));
Console.WriteLine(rewritten.Compile()(2));

public sealed class DoubleConstants : ExpressionVisitor
{
    protected override Expression VisitConstant(ConstantExpression node)
    {
        if (node.Value is int value)
        {
            return Expression.Constant(value * 2, typeof(int));
        }

        return base.VisitConstant(node);
    }
}

The visitor doubles every integer constant in the tree. The original lambda computes n * 3 + 4; the rewritten one computes n * 6 + 8.

protected override Expression VisitConstant(ConstantExpression node)
{
    if (node.Value is int value)
    {
        return Expression.Constant(value * 2, typeof(int));
    }

    return base.VisitConstant(node);
}

VisitConstant is called for the constants 3 and 4, but not for the parameter n. Returning a new node replaces it in the parent automatically; the visitor rebuilds only the nodes whose children changed. The cast at the call site restores the typed Expression<Func<int, int>>.

$ dotnet run
n => ((n * 3) + 4)
n => ((n * 6) + 8)
10
20

Translating a tree

A translator is a visitor that writes text instead of returning a new tree. This is the core of a LINQ provider: the provider visits the predicate and emits the syntax of the target system. The example below handles comparisons, and/or, member access, and constants.

Program.cs
using System.Linq.Expressions;
using System.Text;

Expression<Func<Person, bool>> predicate = p => p.Age >= 18 && p.Name != "Bob";
Console.WriteLine("WHERE " + new SqlVisitor().Translate(predicate.Body));

public sealed class SqlVisitor : ExpressionVisitor
{
    private readonly StringBuilder _sql = new();

    public string Translate(Expression expression)
    {
        Visit(expression);
        return _sql.ToString();
    }

    protected override Expression VisitBinary(BinaryExpression node)
    {
        _sql.Append('(');
        Visit(node.Left);
        _sql.Append(node.NodeType switch
        {
            ExpressionType.AndAlso => " AND ",
            ExpressionType.OrElse => " OR ",
            ExpressionType.Equal => " = ",
            ExpressionType.NotEqual => " <> ",
            ExpressionType.GreaterThan => " > ",
            ExpressionType.GreaterThanOrEqual => " >= ",
            ExpressionType.LessThan => " < ",
            ExpressionType.LessThanOrEqual => " <= ",
            _ => throw new NotSupportedException(node.NodeType.ToString())
        });
        Visit(node.Right);
        _sql.Append(')');

        return node;
    }

    protected override Expression VisitMember(MemberExpression node)
    {
        _sql.Append(node.Member.Name);
        return node;
    }

    protected override Expression VisitConstant(ConstantExpression node)
    {
        if (node.Value is string text)
        {
            _sql.Append('\'').Append(text.Replace("'", "''")).Append('\'');
        }
        else
        {
            _sql.Append(node.Value);
        }

        return node;
    }
}

public sealed record Person(string Name, int Age);

The predicate combines an age check and a name check. The visitor turns it into a WHERE clause with SQL operators and quoted strings.

_sql.Append(node.NodeType switch
{
    ExpressionType.AndAlso => " AND ",
    ExpressionType.OrElse => " OR ",
    ExpressionType.NotEqual => " <> ",
    ...
});

C# uses &&, ||, and !=; SQL uses AND, OR, and <>. The switch maps one set of operators to the other. Parentheses preserve the grouping, and string constants are quoted, with embedded quotes doubled. A real provider also parameterizes values instead of embedding them, which avoids SQL injection.

$ dotnet run
WHERE ((Age >= 18) AND (Name <> 'Bob'))

Delegates and expression trees

The same lambda can often be converted to both a delegate and an expression tree, and the difference matters. A Func<T> is compiled code that runs directly. An Expression<Func<T>> is data that must be interpreted or compiled before it runs. Methods that take Func<T> see only the result; methods that take Expression<Func<T>> can see the structure.

Not every lambda can become an expression tree. Statement-bodied lambdas, async lambdas, and some newer syntax are rejected at compile time because the tree format has no node for them. Expression trees describe expressions, not arbitrary statements. This is also why IQueryable<T> providers have a limited vocabulary: they can translate only the nodes they understand, and the rest must be evaluated on the client.

For in-memory work, prefer a plain delegate. Use an expression tree when something else has to read the code: a database provider, a rule engine, a serializer, or a dynamic query builder. The lambda expression tutorial covers the delegate side, and LINQ query expression shows how query syntax becomes method calls and trees.

Source

Expression trees

Expression class

ExpressionVisitor class

In this article we have inspected, built, rewritten, and translated C# expression trees. See also the lambda expression, delegate, LINQ query expression, and Func 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.