Expression Trees · TL;DR

1 min read
Senior10 min read
Rapid overview

TL;DR

An expression tree is code represented as data: an immutable tree of objects from System.Linq.Expressions that describes an expression (parameters, constants, member accesses, operators, method calls) instead of executing it. When a lambda is assigned to Expression<Func<…>>, the compiler emits code that builds that tree at runtime instead of compiling the lambda to IL. Programs can then inspect it (EF Core translates it to SQL; FluentValidation and AutoMapper read which property x => x.Email points at), rewrite it (ExpressionVisitor), or turn it into executable code with Compile(), which generates IL at runtime and is expensive, so compiled delegates must be cached. You can also build trees by hand with the Expression.* factory methods, for dynamic filters, sorting and fast property accessors. Limits: the C# compiler only converts expression lambdas without statement bodies, assignments, ?., async, tuple literals and some newer syntax. Memory: every node is a heap object and the tree is rebuilt each time the code that creates it runs.

See also