C# Interview Question #121
What is an expression tree in C#?
Advanced LINQ, Expressions & Collections Senior Advanced
Quick Interview Answer
An expression tree represents code as a tree-like data structure rather than immediately compiling it into executable instructions.
Detailed Explanation
An expression tree represents code as a tree-like data structure rather than immediately compiling it into executable instructions.
Expression trees are commonly represented by Expression<TDelegate>. Libraries can inspect the tree and translate its operations into another language or query format.
Entity Framework Core relies heavily on expression trees. For example, when a Where expression is applied to IQueryable<T>, EF Core can inspect the expression and translate supported operations into SQL.
This is one of the major differences between delegates and expression trees: a delegate represents executable code, while an expression tree represents the structure of code that can be analyzed.
Code Example
Expression<Func<Product, bool>> filter =
p => p.Price > 1000;
// The expression can be inspected or translated
// rather than only executed directly.