C# Reference ยท Reflection, Attributes and Metadata
Expression trees and compiled lambdas
Reference for C# expression trees: Expression<Func<T>>, building trees by hand, inspecting them, compiling to delegates and caching for fast reflection.
An expression tree is a data structure that represents code. When you assign a lambda to Expression<Func<int, int>> instead of Func<int, int>, the compiler does not produce a delegate; it produces a tree of Expression objects (BinaryExpression, ParameterExpression, ConstantExpression and so on) that describes the lambda. You can walk that tree, translate it to another language (LINQ providers turn it into SQL) or call Compile() to get a real delegate at run time.
Building trees by hand with the Expression factory methods also gives you a way to generate fast code on the fly, for example a typed getter for a property found by reflection. After the one-time compile cost, calling the delegate is nearly as fast as ordinary code.
Expression<Func<int, int>> square = x => x * x; Func<int, int> f = square.Compile(); Console.WriteLine(f(5)); // 25
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<TDelegate> e = lambda; // compiler builds the tree TDelegate d = e.Compile(); // tree -> delegate (one-time cost) Expression.Lambda<TDelegate>(body, parameters) // build by hand
| Member | Description |
|---|---|
Expression.Parameter(Type, name) |
A lambda parameter. |
Expression.Constant(value) |
A literal value. |
Expression.Property, Field, Call |
Member access and method calls. |
Expression.Add, Multiply, Equal, AndAlso, Condition |
Operators and branches. |
Expression.Convert |
Casts, including boxing to object. |
Expression.Block, Assign, Loop, TryCatch |
Statement-like nodes (cannot be produced from C# lambdas, only built by hand). |
ExpressionVisitor |
Base class for walking or rewriting a tree. |
Errors: building a node with mismatched types throws InvalidOperationException or ArgumentException (for example adding an int to a string); Compile() throws if the tree references a parameter that is not in scope.
Usage notes
- Only expression lambdas convert to trees. Statement lambdas (
x => { ... }),asynclambdas,refparameters, dynamic operations and?.cannot be turned into expression trees by the compiler (error CS0834 and related). - Compile once, cache the delegate.
Compile()costs milliseconds; the resulting delegate runs at normal speed. Never compile inside a loop. - Trees are immutable. To change one, use an
ExpressionVisitorthat returns a new tree. - Captured variables become fields on a closure object that shows up in the tree as a
ConstantExpression, a common surprise when printing trees. - LINQ providers (
IQueryable<T>) takeExpression<Func<...>>so they can translate the query; the same lambda passed toIEnumerable<T>runs as plain code. - Native AOT:
Compile()needs dynamic code generation, which Native AOT does not have. It falls back to a slow interpreter or fails; see Native AOT and trimming. - Alternatives: a source generator or
MethodInfo.CreateDelegatecan avoid the compile step.