Expression Trees
By the end of this lesson you'll be able to treat a piece of C# logic as data you can read, build, and rewrite at runtime — then compile it back into runnable code. This is the machinery behind LINQ providers and ORMs like Entity Framework, which read your queries and translate them into SQL.
Part of the free C# course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
💡 Real-World Analogy
A compiled lambda (a Func ) is like a cooked meal — you can eat it, but you can't see the recipe or change the ingredients. An expression tree is the recipe written down as a list of steps : because it's just data, you can read each step, swap an ingredient, translate it into another language, or finally cook it (that's Compile() ) whenever you're ready. Entity Framework needs the recipe, not the meal — it reads your p => p.Price > 100 recipe and rewrites it as WHERE Price > 100 SQL before any data is fetched.
📊 The Expression API at a Glance
Member
What it does
Example
Returns
Expression < T >
A lambda stored as data
Expression < Func < int,int >>
a tree
.Compile()
Turn the tree into code
expr.Compile()
a delegate
.Body / .NodeType
Inspect the tree
expr.Body.NodeType
a node / kind
Expression.Parameter
Make a parameter node
Parameter(typeof(int),"a")
a node
Expression.Add
Make a + node
Add(a, b)
Expression.Lambda
Wrap a body + params
Lambda < Func < ... >> (body, a)
ExpressionVisitor
Walk / rewrite a tree
visitor.Visit(expr)
a new tree
Everything lives in System.Linq.Expressions . Forget that using and none of the Expression.* factory methods will be in scope.
Running C# locally: install the .NET SDK or use dotnetfiddle.net . Every example below needs using System.Linq.Expressions; at the top.
1. Expression < Func > vs a Plain Func
Write (a, b) => a + b and what you get depends on the type you store it in . Store it in a Func<int, int, int> and the compiler turns it into IL — runnable machine code you can call but never look inside. Store the identical lambda in an Expression<Func<int, int, int>> and the compiler instead builds a tree of objects describing the code: a Lambda node, with a parameter list and an Add node inside it. The tree is data, so you can read it, take it apart, and only later compile it into a delegate. Read this worked example, run it, then you'll write your own.
Your turn. The program below is almost complete — store a lambda as an expression tree, then compile it so you can call it. Fill in the two blanks marked ___ using the hints, then run it.
2. Building a Tree by Hand
The compiler builds a tree for you from a lambda, but you can also assemble one node by node with the Expression factory methods — that's how dynamic code does it when the logic isn't known until runtime. The pattern is always the same: make the parameter nodes with Expression.Parameter , combine them into a body ( Expression.Add , Expression.Subtract , Expression.Multiply , …), then wrap the body and its parameters in an Expression.Lambda < T > . Compile, and you have a delegate. Now you try: build (x, y) => x - y by hand.
3. Why LINQ Providers & ORMs Need Trees
This is the reason expression trees exist. When you write dbContext.Products.Where(p => p.Price > 100) , Entity Framework Core doesn't run that lambda in C#. It can't — the data is in a database. Instead, Where on an IQueryable<T> takes an Expression , so EF receives the tree , walks it, and translates p.Price > 100 into WHERE [Price] > 100 SQL. A plain Func would be a sealed black box it could only run in memory — meaning it would download every row first. The tree is glass : the provider can see through it.
4. Inspecting & Rewriting with ExpressionVisitor
Once you have a tree you'll often want to walk it — to inspect it, optimise it, or rewrite parts of it. ExpressionVisitor is the built-in walker: subclass it and override a Visit* method (like VisitBinary for + , - , > nodes) to intercept and replace nodes. Trees are immutable — you never edit one in place, you return a new tree. This example swaps every addition for a multiplication, then inspects a node's parts directly.
🔎 Deep Dive: Compile() is not free
Storing a lambda as an Expression and calling .Compile() does real work at runtime — it generates IL on the fly. That's far slower than a lambda the C# compiler turned into a Func ahead of time, and slower still if you do it inside a loop.
Rule of thumb: only reach for expression trees when you genuinely need code-as-data (a query provider, a dynamic rule engine, a mapper). For everyday logic a normal lambda is simpler and faster — compile once and cache the result if you must compile at all.
Pro Tips
- 💡 EF Core needs Expression , not Func : on an IQueryable<T> , .Where(expr) translates to SQL. Pass a Func and you fall back to IEnumerable , pulling every row into memory first.
- 💡 Compile once, reuse: .Compile() generates IL at runtime and is expensive. Cache the resulting Func rather than recompiling.
- 💡 Trees are immutable: you never modify a node — you build a new tree. ExpressionVisitor.Visit returns the new one.
- 💡 Expression lambdas are single-expression only: n => n > 10 is fine; a statement body with { braces, if , or a local variable cannot be assigned to Expression<Func<>> .
- 💡 Libraries make composition easy: LINQKit's PredicateBuilder combines Expression<Func<T,bool>> predicates with AND/OR far more cleanly than hand-building AndAlso nodes.
Common Errors (and the fix)
- Calling the tree directly: addExpr(3, 5) won't compile — an Expression isn't callable. Fix: addExpr.Compile()(3, 5) , or compile once and call the delegate.
- "CS0834: A lambda expression with a statement body cannot be converted to an expression tree": you wrote n => { return n > 10; } . Expression lambdas allow only a single expression. Fix: drop the braces — n => n > 10 .
- "CS1660 / cannot convert lambda to Func " when you meant a tree (or vice versa): you mixed up Expression<Func<int,bool>> and Func<int,bool> . They are different types — a tree is data, a Func is compiled code. Fix: match the variable's type to what you need (inspectable vs runnable).
- "CS0103: The name 'Expression' does not exist in the current context": you're missing the namespace. Fix: add using System.Linq.Expressions; at the top of the file.
- "InvalidOperationException: The LINQ expression could not be translated": EF Core couldn't turn part of your tree into SQL (e.g. a custom C# method). Fix: simplify the predicate, or call .AsEnumerable() first to finish that part in memory.
📋 Quick Reference
Task
Code
Result
Store as a tree
Expression < Func < int,int >> e = n => n*2;
Run a tree
var f = e.Compile(); f(5);
10
Inspect a node
e.Body.NodeType
Multiply
Parameter node
Expression.Parameter(typeof(int),"a")
Add node
Expression.Add(a, b)
Wrap a lambda
Expression.Lambda < Func < ... >> (body, a, b)
Rewrite a tree
new MyVisitor().Visit(e)
Frequently Asked Questions
Q: What's the actual difference between Func<int,bool> and Expression<Func<int,bool>> ?
A Func is compiled, runnable code — a black box you can only call. An Expression is a data structure describing that same code, which you can read, modify, or translate before (optionally) compiling it into a Func . Same lambda syntax, completely different capability.
Q: Why won't my expression lambda accept an if or curly braces?
C#'s lambda-to-tree conversion only supports a single expression (like n => n > 10 ), not a statement body with { braces, loops, or local variables. If you need statements you must build the tree explicitly with the factory methods, or just use a Func .
Q: How does Entity Framework turn my C# into SQL?
Your Where(p => ...) lands on an IQueryable<T> whose Where takes an Expression . EF walks that tree, recognises nodes like a property access and a > comparison, and emits the matching SQL — all without ever running your lambda in C#.
Q: Do I need expression trees for everyday code?
Rarely. Reach for them when you need code-as-data: a query provider, a dynamic rule/filter builder, an object mapper, or a mocking framework. For ordinary logic a normal lambda is simpler, faster, and clearer — don't add a tree where a Func will do.
Mini-Challenge: A Compiled Predicate
No blanks this time — just a brief and an outline to keep you on track. Build a predicate expression n => n > 10 , compile it into a Func<int, bool> , and test it on a few values. Print the tree's body too, so you can see the code as data. Run it and check your output against the expected lines in the comments.
🎉 Lesson Complete
- ✅ Expression<Func<T>> stores a lambda as inspectable data ; Func<T> stores it as compiled code
- ✅ A tree is data — call .Compile() to turn it into a runnable delegate before invoking it
- ✅ Build trees by hand with Expression.Parameter , Expression.Add and Expression.Lambda
- ✅ Inspect any node through .Body and .NodeType
- ✅ LINQ providers and ORMs need the tree so they can translate your query to SQL
- ✅ ExpressionVisitor walks and rewrites trees, always returning a new (immutable) tree
- ✅ Next lesson: Reflection — inspecting types, methods, and attributes at runtime
Practice quiz
What is the difference between Func<int,int> and Expression<Func<int,int>>?
- They are identical
- Expression is faster to call
- Func is compiled runnable code; Expression is an inspectable data structure (a tree)
- Func can be translated to SQL
Answer: Func is compiled runnable code; Expression is an inspectable data structure (a tree). A Func is compiled IL you can only run; an Expression is a tree of objects describing the code, which you can read, rewrite, then compile.
How do you run an expression tree?
- Call .Compile() to turn it into a delegate first
- Call it directly like a method
- Use .Invoke() on the tree
- Cast it to a Func
Answer: Call .Compile() to turn it into a delegate first. An Expression isn't callable. You must call .Compile() to produce a delegate, then invoke that delegate.
What does do if addExpr is an Expression<Func<int,int,int>>?
- Returns 8
- Returns the tree
- Throws at runtime
- Won't compile — an Expression isn't callable
Answer: Won't compile — an Expression isn't callable. Calling the tree directly won't compile; you need addExpr.Compile()(3, 5).
Which factory method makes a parameter node?
- Expression.Lambda
- Expression.Parameter
- Expression.Add
- Expression.Variable only
Answer: Expression.Parameter. Expression.Parameter(typeof(int), "a") creates a parameter node; you then combine nodes and wrap them in Expression.Lambda.
How do you inspect a node's kind (e.g. Add vs Subtract)?
- .NodeType
- .Compile()
- .Invoke()
- .GetType().Name only
Answer: .NodeType. Every node exposes its kind through .NodeType (e.g. Add, Subtract), and the lambda's body through .Body.
Why do LINQ providers and ORMs like EF Core need expressions, not Funcs?
- Expressions run faster in memory
- Funcs can't take parameters
- They can read the tree and translate it into SQL
- Expressions use less memory
Answer: They can read the tree and translate it into SQL. On an IQueryable<T>, Where takes an Expression so the provider can walk the tree and translate it into SQL — a Func would be a black box it could only run in memory.
What does ExpressionVisitor let you do?
- Compile a tree to SQL directly
- Walk a tree node by node to inspect or replace nodes
- Run the tree on a remote server
- Delete nodes from a tree in place
Answer: Walk a tree node by node to inspect or replace nodes. Subclass ExpressionVisitor and override a Visit method (like VisitBinary) to intercept and replace nodes as you walk the tree.
Are expression trees mutable?
- Yes, you edit nodes in place
- Only the root node is mutable
- Only after Compile()
- No — they are immutable; you return a new tree
Answer: No — they are immutable; you return a new tree. Trees are immutable; a visitor never edits one in place, it returns a brand-new tree (ExpressionVisitor.Visit returns the new one).
What kind of lambda body can be assigned to an Expression<Func<>>?
- A statement body with braces and an if
- Only a single expression (e.g. n => n > 10)
- Any method body
- Only a body with a return statement
Answer: Only a single expression (e.g. n => n > 10). Expression lambdas allow only a single expression. A statement body with { } braces, if, or local variables cannot be converted to an expression tree (CS0834).
What is the performance caveat with .Compile()?
- It is free and instant
- It only works once per tree
- It generates IL at runtime and is expensive — compile once and reuse
- It always runs on a background thread
Answer: It generates IL at runtime and is expensive — compile once and reuse. .Compile() generates IL on the fly at runtime, which is slow — especially in a loop. Compile once and cache the resulting delegate.
Continue this course
- Previous: Events: Advanced Patterns
- Next: Reflection