C#
Lambda to expression
Learn to convert lambdas to expression trees.
Converting lambdas to expressions
A lambda is automatically converted to an expression tree when the target type is Expression<T>. The same lambda assigned to Func<T> becomes a delegate; assigned to Expression<Func<T>> it becomes data. The conversion happens at compile time.
But not every lambda converts. Only expression lambdas (single expression body) convert. Statement lambdas (block body in { }) cannot become expression trees; they can only be delegates.
Which lambdas convert?
Only expression lambdas convert to expression trees. x => x * 2 has a single expression body; it converts. x => { return x * 2; } is a statement block; it does not convert and produces a compile error.
This restriction exists because expression trees can only represent certain constructs, not every C# statement. Assignments, if, for and other statements have no expression-tree form. For complex logic, use delegates.
Exercise Convert a lambda to expression and print Body
Convert a lambda to an expression tree with Expression<Func<int, int>> square = x => x * x;. Print square.Body with Console.WriteLine.
Show example solution
Define the expression tree with Expression<Func<int, int>> square = x => x * x;. Then print Body with Console.WriteLine(square.Body);.
Example solution:
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<int, int>> square = x => x * x;
Console.WriteLine(square.Body);
}
}
Test yourself
-
Complete the expression tree type
Func<int, int> d = x => x * 2; Expression<____<int, int>> e = x => x * 2;
Show answer
Func<int, int> d = x => x * 2; Expression<Func<int, int>> e = x => x * 2;
-
Which cannot be converted to an expression tree?
x => { return x * 2; }
- x => { return x * 2; }
- x => x * 2
- (a, b) => a + b
- () => 42
Show answer
x => { return x * 2; } — Correct. Statement lambdas cannot convert to expression trees.
-
Match lambda kind to convertibility
- x => x * 2
- Single expression - convertible
- x => { return x; }
- Statement block - not convertible
- (a, b) => a + b
- Two params - convertible
- x => { var y = x; return y; }
- Multi-statement - not convertible
Next lesson: Inspecting expression body