In C#, what does the compiler produce when the same lambda is assigned to a Func<Order, bool> and to an Expression<Func<Order, bool>>?
answer
- same text, two conversions
- code versus data
- Body, Parameters, NodeType
- Compile() before you can call it
- expression-bodied lambdas only
basics
~20 sAssigned to Func<Order, bool>, the lambda compiles to a method you call through a delegate. Assigned to Expression<Func<Order, bool>>, the compiler emits code that builds a tree describing the lambda: data you inspect, translate or Compile() into a delegate.
solid answer
~40 sThe target type decides what a lambda becomes. For `Func<Order, bool>` the compiler emits the body as IL in a generated method and creates a delegate pointing at it, which you call directly. For `Expression<Func<Order, bool>>` it emits calls to factory methods such as `Expression.Parameter`, `Expression.Property` and `Expression.Lambda`, so at run time you hold an `Expression<TDelegate>` object with `Parameters`, a `Body` and nodes like `GreaterThan`. You cannot invoke it (`e(order)` is error CS0149, "Method name expected"); `Compile()` turns it into a `Func<Order, bool>`. There is no conversion from a delegate back to a tree (CS0029), and only expression-bodied lambdas convert: a block body is CS0834, and `?.` (CS8072), a call to a local function (CS8110) or a switch expression (CS8514) are rejected as well.
code
csharp · 16 linesusing System.Linq.Expressions;
decimal min = 100m;
Func<Order, bool> asDelegate = o => o.Total > min;
Expression<Func<Order, bool>> asTree = o => o.Total > min;
Console.WriteLine(asDelegate(new Order(250m))); // True: call it directly
Console.WriteLine(asTree.Body.NodeType); // GreaterThan
Console.WriteLine(asTree.Parameters[0].Name); // o
Console.WriteLine(asTree);
// o => (o.Total > value(Program+<>c__DisplayClass0_0).min)
Func<Order, bool> compiled = asTree.Compile();
Console.WriteLine(compiled(new Order(40m))); // False
record Order(decimal Total);go deeper
Recall that the same lambda can become a Func you call or an Expression<Func> that describes the code, and that an expression tree must be compiled before it can run.
Explain what the compiler emits in each case: IL in a method plus a delegate, or Expression factory calls that build a tree, and why captured locals show up as closure field reads.
Show the limits you meet in real code: block bodies, ?. and switch expressions are rejected in trees, delegates never convert back, and Compile() should run once and be cached.
Weigh where trees earn their cost: they let a provider or a rules engine read code as data, but they constrain the syntax a team can use and add compile cost on in-memory paths.
## One lambda, two conversions A C# lambda has no type of its own until it meets a target. The same text, `o => o.Total > min`, can be converted to two very different things: - **A delegate type** such as `Func<Order, bool>`. The compiler emits the body as IL in a generated method (on a closure class when it captures locals) and creates a delegate instance that points at it. Calling the delegate runs compiled code. - **An expression tree type**, `Expression<TDelegate>`. The compiler emits code that, at run time, calls `System.Linq.Expressions.Expression` factory methods to build an object graph describing the lambda: a `ParameterExpression` for `o`, a `MemberExpression` for `o.Total`, a `BinaryExpression` of type `GreaterThan`, and a `LambdaExpression` on top. Nothing in that graph is executable on its own. That difference is why LINQ has two operator sets: `Enumerable` methods take delegates and run them, `Queryable` methods take expression trees and hand them to a provider that can read them. ## What the tree looks like An `Expression<Func<Order, bool>>` exposes the lambda as data: - `Parameters` holds the `ParameterExpression` objects (`o`). - `Body` is the root of the lambda body; its `NodeType` here is `ExpressionType.GreaterThan`, with `Left` and `Right` children. - A **captured local** does not appear as its value. It appears as a field read on the compiler-generated closure object: printing the tree shows `value(Program+<>c__DisplayClass0_0).min`. A provider evaluates that member when it runs the query, so a later change to `min` is seen by the next execution. - `ToString()` prints a readable form such as `o => (o.Total > value(...).min)`, which is handy in logs and tests. Expression trees are **immutable**: to change one you build a new tree, usually with an `ExpressionVisitor` that copies the nodes it does not change. Because the tree is plain data, code can walk it: a query provider reads `NodeType` and the children of each node and decides what to emit, a logging helper prints it, and a test can assert on its shape. None of that is possible with a delegate, whose only operation is being invoked. The trade is one-way, though: a tree can always become a delegate through `Compile()`, but a delegate never becomes a tree. ## Running a tree: Compile() 1. `Expression<TDelegate>.Compile()` returns a `TDelegate`, here a `Func<Order, bool>`. The non-generic `LambdaExpression.Compile()` returns `Delegate`, which you cast. 2. Compiling is expensive compared with calling the result: it generates code, or builds an interpreter where dynamic code is not supported. Compile once and keep the delegate. 3. `Compile(preferInterpretation: true)` asks for the interpreter explicitly, usually trading slower calls for a cheaper compile step. You cannot call a tree directly: `e(order)` fails with CS0149, "Method name expected". ## What cannot go in a tree The compiler converts only lambdas whose shape the expression-tree model can represent, and rejects the rest at compile time: | Construct in the lambda | Diagnostic | |---|---| | A block body, `o => { return ...; }` | CS0834 | | An assignment operator | CS0832 | | The null-conditional `?.` | CS8072 | | A call to a local function | CS8110 | | A switch expression | CS8514 | | An `async` lambda | CS1989 | There is also **no conversion from a delegate to a tree**. Assigning a `Func<Order, bool>` variable to an `Expression<Func<Order, bool>>` is CS0029: once code is compiled, no description of it remains to recover. Writing `o => f(o)` compiles, but the tree then holds an `Invoke` node around an opaque delegate that a provider cannot look inside. ## Why the distinction matters A delegate can only be run. A tree can be **inspected, rewritten, translated or compiled**, which is what lets a query provider turn a C# predicate into another query language, and what lets code build a filter at run time. The price is restrictions on what the lambda may contain and the cost of `Compile()` when you do want to run it in memory. ## Interview angle State the rule as "the target type decides": the same lambda becomes a method plus a delegate, or a description built from `Expression` factory calls. Then show you know the consequences: trees are data you `Compile()` to run, they reject block bodies and newer syntax such as `?.`, and a delegate never turns back into a tree.
- Why can't you pass an existing Func<Order, bool> where an Expression<Func<Order, bool>> is expected?The conversion to an expression tree is a compile-time conversion of lambda syntax: the compiler reads the lambda's text and emits code that describes it. A delegate is already compiled code with no description left to recover, so the assignment is CS0029. Wrapping it as `o => f(o)` compiles, but the tree only holds an `Invoke` of an opaque delegate, which a provider cannot translate.
- How expensive is Expression<TDelegate>.Compile(), and what do you do about it?It generates code for the whole tree, or builds an interpreter where dynamic code is not supported, such as Native AOT, so it costs far more than invoking the result. Compile a tree once and keep the delegate, for example in a static field. Microsoft's documentation advises against caching schemes that compare arbitrary trees, because the comparison can cost more than the compile it saves.
A delegate is a sealed music box: wind it up and it plays the tune, and that is all it can do. An expression tree is the sheet music: a musician can read it, transpose it for another instrument, or build a music box from it. From the sealed box alone, nobody recovers the score.
- An Expression<Func<T, bool>> can be called directly, just like a delegate
- The compiler turns a Func<T, bool> variable into an expression tree when one is needed
- Any lambda, including one with a block body, converts to an expression tree
- You adjust a filter by changing a node of an existing expression tree in place
- Compile() is cheap, so calling it inside a loop costs nothing