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.

Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.

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.

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.

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 and the compiler turns it into IL — runnable machine code you can call but never look inside. Store the identical lambda in an 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 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.

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.

Q: What's the actual difference between and ?

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 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.

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 , 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.

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.