C#
Expression<T>
Learn to define an expression tree with Expression<TDelegate>.
What is Expression<T>?
Expression<TDelegate> is an expression tree that represents a lambda as data. When a lambda is assigned to Func<T> it becomes an executable delegate; when assigned to Expression<Func<T>> it becomes data.
As data, the tree can be inspected via Body, NodeType and Parameters. This is how providers like Entity Framework translate lambdas to SQL. The same lambda becomes either a delegate or data, depending on the target.
Func vs Expression
The same lambda means two things depending on the target. Func<int, int> f = x => x * 2; produces a delegate; you can call f(3). Expression<Func<int, int>> e = x => x * 2; produces data; you can read e.Body.
The compiler chooses how to compile the lambda based on the target type. The same syntax yields two different structures. As data, expression trees power ORMs and dynamic query builders; as delegates, they are used for runtime computation.
Exercise Define an Expression and print NodeType
Define an expression tree with Expression<Func<int, int>> square = x => x * x;. Print square.NodeType with Console.WriteLine.
Show example solution
Define the expression tree with Expression<Func<int, int>> square = x => x * x;. Then print NodeType with Console.WriteLine(square.NodeType);.
Example solution:
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<int, int>> square = x => x * x;
Console.WriteLine(square.NodeType);
}
}
Test yourself
-
What is the difference between Expression and Func?
Func<int, int> d = x => x * 2;
Expression<Func<int, int>> e = x => x * 2;
- They are identical; both are executable
- Func is faster, Expression is slower
- Func is an executable delegate, Expression is an expression tree as data
- Expression is only for async operations
Show answer
Func is an executable delegate, Expression is an expression tree as data — Correct. Func is a delegate, Expression is an expression tree as data.
-
Complete the Expression declaration
Expression<____<int, int>> square = x => x * x;
Show answer
Expression<Func<int, int>> square = x => x * x;
-
Match the type to its content
- Func<int, int>
- Executable delegate
- Expression<Func<int, int>>
- Expression tree as data
- Expression<Func<int, bool>>
- Boolean expression tree
- Func<int, bool>
- Boolean delegate
Next lesson: Lambda to expression