Microsoft Learn

Namespace: System.Linq.Expressions

Namespace: System.Linq.Expressions

Assembly: System.Linq.Expressions.dll

Documentation Version: .NET 8.0

Overview

The System.Linq.Expressions namespace provides types that represent members of expression trees. Expression trees are a way to represent code as a tree structure. This namespace is crucial for scenarios like LINQ providers, dynamic query generation, and creating lambda expressions at runtime.

Classes

Name Description
Expression Represents a node in the expression tree, the root of the expression tree hierarchy.
LambdaExpression Represents a lambda expression, such as a lambda expression statement or a lambda expression that returns a value.
ParameterExpression Represents a parameter in a lambda expression.
ConstantExpression Represents a constant value.
MethodCallExpression Represents a call to a method.
MemberExpression Represents accessing a property or field.
BinaryExpression Represents an expression that has two operands, such as a binary arithmetic operation, comparison, or logical operation.

Usage Example

The following example demonstrates how to build a simple expression tree that represents the operation x + 1 and then compile and execute it.


using System;
using System.Linq.Expressions;

public class Example
{
    public static void Main(string[] args)
    {
        // Create the parameter expression (x)
        ParameterExpression parameterX = Expression.Parameter(typeof(int), "x");

        // Create the constant expression (1)
        ConstantExpression constantOne = Expression.Constant(1, typeof(int));

        // Create the binary expression (x + 1)
        BinaryExpression addExpression = Expression.Add(parameterX, constantOne);

        // Create the lambda expression (x => x + 1)
        Expression<Func<int, int>> lambda = 
            Expression.Lambda<Func<int, int>>(addExpression, parameterX);

        // Compile the lambda expression
        Func<int, int> compiledDelegate = lambda.Compile();

        // Execute the compiled delegate
        int result = compiledDelegate(5);

        Console.WriteLine($"Result of (5 + 1): {result}"); // Output: Result of (5 + 1): 6
    }
}
                

Related Namespaces