Module 1 · Expression Trees, Delegates and Generics · Lesson 1 of 8
Expression trees
You receive num => num < 5. Can your component inspect the number 5, or can it only call the rule? The lambda's target type decides what information it receives.
Start with an inspectable rule
This declaration is a fragment; it assumes System and System.Linq.Expressions are imported.
Expression<Func<int, bool>> isSmall = num => num < 5;
An Expression<Func<int, bool>> is a tree of nodes. Its body describes a comparison; it does not yet test a number. A Func<int, bool> is callable behavior. The distinction matters when a consumer must inspect or translate the rule rather than invoke it locally.
Predict the body text, parameter name and result in this complete small console example.
using System; using System.Linq.Expressions; Expression<Func<int, int, int>> addExpr = (a, b) => a + b; // examine the tree Console.WriteLine(addExpr.Body); // prints "(a + b)" Console.WriteLine(addExpr.Parameters[0].Name); // prints "a" // compile to a delegate and execute Func<int, int, int> addFunc = addExpr.Compile(); Console.WriteLine(addFunc(2, 3)); // prints 5
Compile returns a delegate; calling that delegate with 2 and 3 returns 5. The original tree remains available for inspection. A provider can instead inspect the tree without calling Compile.
Quick check
What does addExpr.Compile() return in the addition example?
Show answer
Correct answer: B
Compile creates the callable delegate; invoking it with 2 and 3 evaluates the addition.
Option A: SQL translation belongs to a provider, not this Compile call.
Option C: Expression compilation does not rewrite the source file.
Option D: The arguments are supplied when the returned delegate is called.
Contract reference: Microsoft documentation.
Choose the representation for the consumer
| Consumer needs | Appropriate input | What still needs checking |
|---|---|---|
| Run a local predicate | Func<T, bool> | Inputs, side effects and failures |
| Inspect or transform a rule | Expression<Func<T, bool>> | Supported nodes and captured state |
| Translate a database filter | An expression accepted by its provider | Translation and results on that provider |
Trees are immutable: a transformation builds replacement nodes, often with ExpressionVisitor. Compiler conversion accepts supported expression lambdas, not statement or async lambdas. Manual construction can represent a broader node set, including blocks and loops, but there is no built-in await node.
Build a filter with optional inputs
The next method belongs inside a class. It assumes Product has non-nullable decimal Price and int CategoryId properties, with System and System.Linq.Expressions imported. Read each conditional as an optional addition to one predicate.
public static Expression<Func<Product, bool>> BuildProductFilter(decimal? minPrice, decimal? maxPrice, int? categoryId)
{
// parameter: product =>
ParameterExpression param = Expression.Parameter(typeof(Product), "product");
Expression body = Expression.Constant(true); // start with 'true'
if (minPrice != null)
{
Expression prop = Expression.Property(param, nameof(Product.Price));
Expression min = Expression.Constant(minPrice.Value);
body = Expression.AndAlso(body, Expression.GreaterThanOrEqual(prop, min));
}
if (maxPrice != null)
{
Expression prop = Expression.Property(param, nameof(Product.Price));
Expression max = Expression.Constant(maxPrice.Value);
body = Expression.AndAlso(body, Expression.LessThanOrEqual(prop, max));
}
if (categoryId != null)
{
Expression prop = Expression.Property(param, nameof(Product.CategoryId));
Expression cat = Expression.Constant(categoryId.Value);
body = Expression.AndAlso(body, Expression.Equal(prop, cat));
}
return Expression.Lambda<Func<Product, bool>>(body, param);
}Before reading the consuming fragment, identify the checks included when minimum is 10m, maximum is 100m and category is 2. Also identify the result when every option is absent.
var filterExpression = BuildProductFilter(10m, 100m, 2); var query = dbContext.Products.Where(filterExpression); // System.Linq; composed, not executed yet
This EF Core sketch needs an application's mapped Products set and live context. It composes a query; construction is not a provider integration test. The constants make tree construction clear, but changing embedded constants repeatedly can harm EF query/plan reuse. For a production query builder, use parameterizable values and inspect commands and results on the intended provider.
Try: find the nodes before running
Predict the parameter name, operation and constant below. Then run the independent example and compare those three observations.
using System;
using System.Linq.Expressions;
Expression<Func<int, bool>> exprTree = num => num < 5;
// Decompose the expression tree
ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];
BinaryExpression body = (BinaryExpression)exprTree.Body;
ParameterExpression left = (ParameterExpression)body.Left;
ConstantExpression right = (ConstantExpression)body.Right;
Console.WriteLine($"{param.Name} => {left.Name} {body.NodeType} {right.Value}"); // Output: num => num LessThan 5Check: the body is LessThan, its left operand is the num parameter, and its right operand is constant 5. The lambda root and comparison body are different nodes.
These next independent snippets assume System, System.Linq and System.Linq.Expressions. Predict the Constant node's type/value, then the addition's parameter count and operation.
var constant = Expression.Constant(24, typeof(int));
Console.WriteLine($"Node type: {constant.NodeType}, Type: {constant.Type}, Value: {constant.Value}"); // Output: Node type: Constant, Type: System.Int32, Value: 24Expression<Func<int, int, int>> addition = (a, b) => a + b;
Console.WriteLine($"Lambda has {addition.Parameters.Count} parameters: " +
string.Join(", ", addition.Parameters.Select(p => p.Name)));
BinaryExpression sumBody = (BinaryExpression)addition.Body;
Console.WriteLine($"Operation: {sumBody.NodeType}, Left: {((ParameterExpression)sumBody.Left).Name}, Right: {((ParameterExpression)sumBody.Right).Name}");Lambda: num => num < 5
|
+-- LessThan
|
+-- Parameter: num
+-- Constant: 5Your design check
For the product filter, write the accepted values at both price endpoints and one outside each endpoint before executing a provider query. Hint: AndAlso combines conditions; it does not repair a node whose constant type disagrees with the property type. Check: the chosen inputs include both endpoints, and a provider test establishes translation as well as returned rows.
Use an ordinary delegate when inspection is unnecessary. Build/compile a stable tree once when reuse justifies it, with an appropriate captured-state lifetime. Tree construction, compilation, interpretation and invocation have different costs; measure the actual path rather than promising a universal speed advantage.
TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·