ExpressionBuilder Class
Namespace: System.Linq.Expressions
Assembly: System.Linq.Expressions.dll
Summary
The ExpressionBuilder class provides a set of static helper methods that simplify the creation of commonly used expression tree nodes.
Syntax
public static class ExpressionBuilder
Methods
| Method | Return Type | Description |
|---|---|---|
Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) |
Expression<TDelegate> |
Creates a lambda expression with the specified body and parameters. |
BinaryExpression Add(Expression left, Expression right) |
BinaryExpression |
Creates an addition expression that adds two operands. |
MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments) |
MethodCallExpression |
Creates a method call expression. |
UnaryExpression Convert(Expression operand, Type type) |
UnaryExpression |
Creates a conversion (cast) expression. |
Example
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
// Parameter: x
var param = Expression.Parameter(typeof(int), "x");
// Body: x + 5
var constant = Expression.Constant(5);
var body = ExpressionBuilder.Add(param, constant);
// Lambda: x => x + 5
var lambda = ExpressionBuilder.Lambda<Func<int, int>>(body, param);
var compiled = lambda.Compile();
Console.WriteLine(compiled(10)); // Output: 15
}
}
Remarks
The helper methods in ExpressionBuilder are thin wrappers around the static factory methods of the Expression class. They exist primarily to improve readability and reduce the amount of boilerplate code required when constructing expression trees.