C# Reference ยท LINQ
Expression trees and Expression<T>
Reference for C# expression trees: Expression<TDelegate>, reading a lambda as data, building trees by hand, Compile(), visitors and what they cannot hold.
An expression tree is a lambda represented as data instead of as compiled code. When you assign a lambda to Expression<Func<T, bool>> rather than to Func<T, bool>, the compiler builds a tree of objects (BinaryExpression, MemberExpression, ConstantExpression, ...) that describes what the lambda does. Your program can then inspect it, rewrite it, translate it to another language (SQL is the classic example) or compile it to a delegate at run time.
Expression trees live in System.Linq.Expressions. They are the mechanism that lets IQueryable<T> providers see the predicate in Where(p => p.Age > 18) and send it to a database, instead of just running it.
using System.Linq.Expressions; Expression<Func<int, bool>> isAdult = age => age >= 18; Func<int, bool> compiled = isAdult.Compile();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
Expression<Func<T, TResult>> expr = x => /* a single expression */;
public sealed class Expression<TDelegate> : LambdaExpression { public Expression Body { get; } public ReadOnlyCollection<ParameterExpression> Parameters { get; } public TDelegate Compile(); }
| Member | Description |
|---|---|
Body |
The root node of the tree (everything to the right of =>). |
Parameters |
The lambda's parameters as ParameterExpression nodes. |
NodeType |
An ExpressionType such as Add, AndAlso, Call, MemberAccess, Constant. |
Compile() |
Generates a delegate of type TDelegate. Compiling is slow; cache the result. |
Expression.* factories |
Add, Call, Constant, Lambda, Property, ... build nodes by hand. |
ExpressionVisitor |
Base class for walking and rewriting trees. |
Returns: Compile() returns a delegate that behaves like the original lambda.
Errors: assigning a lambda with a statement body (braces and statements), an async lambda, or or one containing dynamic operations or assignments is a compile-time error, because the tree cannot represent it.
Usage notes
- Only expression lambdas. The compiler converts single-expression lambdas. Statement bodies,
??=, null-propagating calls (a?.b),dynamicand many newer features are rejected in expression trees. Method calls, member access, operators,new, conditionals, and a few others are fine. - Immutable. Nodes never change; "modifying" a tree means building a new one, usually with an
ExpressionVisitor. - Closures become constants and fields. A captured local appears as a
MemberExpressionover a compiler-generated closure object, which is how providers find parameter values. - Compile once.
Compile()emits IL and is orders of magnitude slower than calling the result. Store the delegate in a static field when the tree is fixed. - Reflection speed-ups. Compiled expression trees are a common way to build fast property getters and object factories at run time, close to the speed of hand-written code.
- Combining predicates needs a shared
ParameterExpression, as in the second example;AndAlso(positive.Body, even.Body)alone would reference two different parameters and fail atCompile(). - Not serializable. Trees are in-memory objects; to send one over the wire you need your own format.
- Not for everyday logic. Prefer a plain delegate (
Func<T, bool>) unless a provider needs to inspect the code. SeeIQueryable<T>.