Expression Class
System.Linq.Expressions
Represents a node in an expression tree.
Summary
The Expression class is the base class for all nodes in an expression tree. Expression trees are a way to represent code as a tree of nodes, where each node represents an operation or a value. This allows for programmatic manipulation and translation of code, such as compiling it into executable code, translating it into SQL queries, or performing analysis.
Derived Classes
The Expression class has many derived classes, each representing a specific type of expression node. Some common derived classes include:
BinaryExpression: Represents a binary operation (e.g., addition, subtraction, comparison).ConstantExpression: Represents a constant value.ParameterExpression: Represents a parameter in a lambda expression.MethodCallExpression: Represents a call to a method.LambdaExpression: Represents a lambda expression.MemberExpression: Represents access to a member (property or field).NewExpression: Represents the creation of a new object.
Represents a lambda expression that can be compiled and executed.
Properties
| Name | Description |
|---|---|
| CanReduce | Gets a value that indicates whether the expression can be reduced. |
| ExpressionType | Gets the ExpressionType of the expression. |
| NodeType | Gets the ExpressionType of the node. |
| Type | Gets the static type of the expression that results from the expression tree. |
Methods
| Name | Description |
|---|---|
Accept(ExpressionVisitor visitor) |
Dispatches to the specific visit method for this node type. |
Compile() |
Compiles the expression tree into executable code. |
Compile(LambdaCompiler lambdaCompiler) |
Compiles the expression tree into executable code using the specified compiler. |
Reduce() |
Reduces the expression tree to its simplest form. |
ToString() |
Returns a string representation of the expression tree. |
ExpressionType Enum
Defines the type of an expression tree node.
Common values include:
ConstantParameterBinaryMemberAccessMethodCallLambdaNew
Example
Creating a simple expression tree to represent the addition of two constants:
using System;
using System.Linq.Expressions;
public class Example
{
public static void Main(string[] args)
{
// Create constant expressions for 5 and 10
ConstantExpression constant5 = Expression.Constant(5, typeof(int));
ConstantExpression constant10 = Expression.Constant(10, typeof(int));
// Create a binary expression for addition
BinaryExpression addition = Expression.Add(constant5, constant10);
// Create a lambda expression from the binary expression
Expression<Func<int>> compiledExpression = Expression.Lambda<Func<int>>(
addition,
Enumerable.Empty<ParameterExpression>()
);
// Compile the expression tree into an executable delegate
Func<int> resultDelegate = compiledExpression.Compile();
// Execute the delegate
int result = resultDelegate();
Console.WriteLine($"Result of expression tree: {result}"); // Output: Result of expression tree: 15
}
}