What Is an Expression Tree
An expression tree is an in-memory data structure that represents code as data — instead of compiling a lambda into executable instructions, the compiler builds a tree of Expression-derived nodes (BinaryExpression, MemberExpression, MethodCallExpression, ParameterExpression, ConstantExpression, and so on) that describe the operations the lambda would perform. Because the tree is just data, it can be inspected, transformed, or translated into an entirely different execution form, such as a SQL SELECT statement, which is exactly what LINQ to Entities does when it receives a query against an IQueryable<T>.
Cricket analogy: An expression tree is like a detailed wagon-wheel and pitch-map dataset recorded for a batter's innings rather than the raw footage; an analyst can walk that structured data to regenerate insights in any format, whether a heat map or a text summary, unlike a video clip which just plays.
Building and Walking an Expression Tree
You can construct expression trees manually using the System.Linq.Expressions API, composing nodes like Expression.Parameter, Expression.Property, Expression.Constant, and Expression.GreaterThan, then compiling the result with Expression<TDelegate>.Compile() to get an executable delegate. Providers walk trees using the visitor pattern: subclassing ExpressionVisitor and overriding methods like VisitBinary or VisitMethodCall lets you traverse and transform a tree, which is exactly how EF Core's query pipeline rewrites a LINQ expression tree into a SQL command tree before generating the final query text.
Cricket analogy: Manually building an expression tree is like a scorer constructing a delivery-by-delivery log node by node, ball, runs, wicket, rather than watching the match live; a visitor pattern is like an analyst later walking that log to compile a bowling economy report.
using System.Linq.Expressions;
// Manually build: p => p.Price > 100
ParameterExpression param = Expression.Parameter(typeof(Product), "p");
MemberExpression priceProp = Expression.Property(param, nameof(Product.Price));
ConstantExpression threshold = Expression.Constant(100m);
BinaryExpression comparison = Expression.GreaterThan(priceProp, threshold);
Expression<Func<Product, bool>> lambda =
Expression.Lambda<Func<Product, bool>>(comparison, param);
// Compile it into an executable delegate
Func<Product, bool> compiled = lambda.Compile();
bool result = compiled(new Product { Price = 150m }); // true
// A simple visitor that finds all ConstantExpression nodes
public class ConstantFinder : ExpressionVisitor
{
public List<object?> Constants { get; } = new();
protected override Expression VisitConstant(ConstantExpression node)
{
Constants.Add(node.Value);
return base.VisitConstant(node);
}
}Why IQueryable Providers Depend on Expression Trees
When you call .Where(), .Select(), or .OrderBy() on an IQueryable<T>, the compiler doesn't just call a method — it builds a MethodCallExpression wrapping the previous query's expression tree plus the new lambda, and the provider's IQueryProvider.CreateQuery is invoked with that combined tree. Only at enumeration time does the provider (e.g. EF Core's relational query pipeline) traverse the full accumulated tree, translate recognized patterns like property access and comparisons into SQL fragments, and throw an informative error for anything it cannot translate, such as calling a custom C# method with no SQL equivalent.
Cricket analogy: This is like a captain layering tactical instructions over after over, field change, then bowling change, then a review request, with the whole sequence only 'read out' as a combined strategy by the analyst at the innings break rather than acted on individually.
Not every C# construct can be translated into SQL. Calling arbitrary instance methods, using complex string formatting, or referencing local functions inside a query against IQueryable<T> will often throw an InvalidOperationException or a 'could not be translated' error at runtime, because the provider's expression tree visitor has no SQL equivalent for that node. Test queries against a real database, not just in-memory fakes, to catch these early.
- An expression tree is data representing code, built from nodes like BinaryExpression and MethodCallExpression.
- Lambdas assigned to Expression<TDelegate> compile to a tree instead of executable IL.
- Expression trees can be built manually via System.Linq.Expressions and compiled with .Compile().
- ExpressionVisitor implements the visitor pattern used to traverse and transform trees.
- IQueryable<T> operators build up a combined expression tree across chained LINQ calls.
- Providers like EF Core walk the accumulated tree at enumeration time to generate SQL.
- Not all C# constructs are translatable to SQL, causing runtime translation errors for unsupported patterns.
Practice what you learned
1. What fundamentally is an expression tree?
2. Which API namespace provides classes for manually building expression trees?
3. What pattern does ExpressionVisitor implement for traversing expression trees?
4. When does an EF Core provider translate an IQueryable's accumulated expression tree into SQL?
5. What typically happens if you use a C# construct with no SQL equivalent inside an IQueryable<T> query?
Was this page helpful?
You May Also Like
Lambda Expressions in LINQ
Understand how lambda expressions power LINQ's filtering, projection, and aggregation operators, and how they differ from anonymous methods and expression trees.
LINQ to SQL and LINQ to Entities
Learn how LINQ to SQL and LINQ to Entities translate C# query expressions into database SQL, and how their architectures differ.
Custom LINQ Extension Methods
Learn how to write your own LINQ-style extension methods on IEnumerable<T>, including deferred execution with yield return and chaining conventions.
Related Reading
Related Study Notes in Microsoft Technologies
Browse all study notesWindows 10 / UWP Development Study Notes
.NET · 30 topics
Microsoft TechnologiesWindows Batch Scripting Study Notes
Batch · 30 topics
Microsoft TechnologiesMFC (Microsoft Foundation Classes) Study Notes
C++ · 30 topics
Microsoft TechnologiesSilverlight Study Notes
.NET · 30 topics
Microsoft TechnologiesXAML Study Notes
.NET · 30 topics
Microsoft TechnologiesWPF (Windows Presentation Foundation) Study Notes
.NET · 30 topics