What are expression trees in C#?
Answer
Expression trees represent code as a data structure (an AST — Abstract Syntax Tree) that can be examined, modified, and compiled at runtime. They are Expression<TDelegate> — lambda expressions that are not compiled to IL but to an object graph representing the code. Example: Expression<Func<int, bool>> expr = x => x > 5; — expr is a tree, not a delegate. Inspect: expr.Body (BinaryExpression), expr.Parameters[0]. Compile to a delegate: var func = expr.Compile();. EF Core uses expression trees extensively — LINQ queries are represented as expression trees and translated to SQL. Useful for: (1) Building dynamic queries. (2) Creating fast property accessors without reflection overhead. (3) Dynamic code generation. (4) LINQ providers (LINQ to SQL, EF Core). Limitations: expression trees don't support statement lambdas, async, or patterns — only single-expression lambdas can be expression trees.
Previous
What is options pattern in ASP.NET Core?
Next
What is the difference between value tasks and tasks in C#?
More C# / .NET Questions
View all →- Advanced What is the difference between value tasks and tasks in C#?
- Advanced What is Native AOT compilation in .NET?
- Advanced What are channels in C# and how do they work?
- Advanced What is the IAsyncEnumerable interface and how is it used?
- Advanced What are covariance and contravariance in C# generics?