Inspecting expression body
Learn to read Expression Body, NodeType and Parameter.
Inspecting the expression body
You traverse an expression tree with Body, NodeType, Parameters and Type. NodeType gives the operation kind (e.g. Add, Multiply, Lambda).
Body holds the inner expression. For x => x * x, Body is a Multiply node; Body.NodeType returns Multiply. This is how ORMs understand the query.
Reading parameters
expr.Parameters is the list of lambda parameters. Each element is a ParameterExpression with Name and Type properties. The lambda (a, b) => a + b contains two parameters.
Reading parameters is essential when reconstructing an expression tree or translating it to another form (e.g. SQL). Providers use this list to map each parameter to a column.
Exercise Inspect the expression body
Define a two-parameter expression tree with Expression<Func<int, int, int>> add = (a, b) => a + b;. Print add.Body.NodeType and add.Body separately with Console.WriteLine.
Show example solution
Define the expression tree with Expression<Func<int, int, int>> add = (a, b) => a + b;. Then call Console.WriteLine(add.Body.NodeType); and Console.WriteLine(add.Body);.
Example solution:
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<int, int, int>> add = (a, b) => a + b;
Console.WriteLine(add.Body.NodeType);
Console.WriteLine(add.Body);
}
}
Test yourself
-
Match NodeType value to its meaning
- Lambda
- Lambda expression
- Multiply
- Multiplication
- Add
- Addition
- Constant
- Constant value
-
Get the first parameter name
var name = expr.____[0].Name;Show answer
var name = expr.Parameters[0].Name; -
What does NodeType return?
- The parameter list of the lambda
- The operation kind of the expression (Multiply, Add, ...)
- The result value
- The string form of the expression
Show answer
The operation kind of the expression (Multiply, Add, ...) — Correct. NodeType returns the operation kind of the expression.