0
0
CsharpConceptBeginner · 3 min read

What is Expression Tree in C#: Explanation and Example

An expression tree in C# is a data structure that represents code as a tree of expressions, like a map of operations and values. It allows programs to inspect, modify, or execute code dynamically at runtime.
⚙️

How It Works

Think of an expression tree as a map of a recipe. Instead of just cooking the dish, you have a detailed plan showing each step and ingredient. In C#, an expression tree breaks down code into parts like operations, variables, and constants, arranged in a tree structure.

This tree structure lets your program look at the code itself, change it, or even build new code on the fly. For example, you can take a mathematical formula written as code and examine each operation separately, or convert it into a different form.

Expression trees are especially useful when you want to create flexible programs that can adapt their behavior without rewriting code manually.

💻

Example

This example shows how to create a simple expression tree for the formula x + 2 and then compile and run it.

csharp
using System;
using System.Linq.Expressions;

class Program
{
    static void Main()
    {
        // Create a parameter expression for 'x'
        ParameterExpression paramX = Expression.Parameter(typeof(int), "x");

        // Create a constant expression for '2'
        ConstantExpression constTwo = Expression.Constant(2, typeof(int));

        // Create an addition expression 'x + 2'
        BinaryExpression body = Expression.Add(paramX, constTwo);

        // Build a lambda expression: x => x + 2
        Expression<Func<int, int>> exprTree = Expression.Lambda<Func<int, int>>(body, paramX);

        // Compile the expression tree into executable code
        Func<int, int> func = exprTree.Compile();

        // Run the function with input 3
        int result = func(3);

        Console.WriteLine(result);
    }
}
Output
5
🎯

When to Use

Use expression trees when you need to work with code as data. This is common in:

  • Building dynamic queries, like in LINQ providers that translate code to database queries.
  • Creating flexible rules or filters that can be changed at runtime.
  • Writing libraries that analyze or transform code, such as compilers or code generators.

They help programs understand and modify logic without hardcoding every possibility.

Key Points

  • Expression trees represent code as a tree of expressions.
  • They allow inspection, modification, and dynamic execution of code.
  • Commonly used in LINQ and dynamic query generation.
  • They improve flexibility by treating code as data.

Key Takeaways

Expression trees let you represent and manipulate code as data structures in C#.
They are useful for building dynamic queries and flexible runtime logic.
You can compile expression trees into executable code to run dynamically created logic.
Expression trees are essential in LINQ providers and code analysis tools.