C# Expression Trees Simplified

Yashaswi Yogeshwara
2 min readMay 10, 2018

--

Expression is a sequence of one or more operands and zero or more operator that can be evaluated to single value, object or method.

Examples:

x+y is an expression

a = x+y is an expression statement.

Expression Tree is simply a group of expressions.

Expression Tree can be constructed using single line lambda expression and also using API.

Lets look at the below example to see how an Expression Tree is constructed using both single line Lambda expression and also using API.

In the above example there are three methods doing the same function, which is, returning the sum of 1+2

Lets start with the first method

SumByLambda()

In this method an anonymous function is created to sum 1+2 . This anonymous function is executed in the next line and the value is returned.

Func<int> sumLambda = () => 1 + 2;
return sumLambda();

Second method

SumByExpressionLambda()

In this method an Expression is created using a Lambda Expression. This expression is compiled and then executed.

//An Expression is created 
Expression<Func<int>> sumExpr = () => 1 + 2;
//The Expression is compiled to an Anonymous Function
Func<int> lambdaExpr = sumExpr.Compile();
// The Anonymous Function is executed
return lambdaExpr();

Third Method

// statement 1
Expression<Func<int>> sumExpr =
Expression.Lambda<Func<int>>(
Expression.Add(
Expression.Constant(1, typeof(int)),
Expression.Constant(2, typeof(int))
)
);

In the above statement an Expression Tree is created using the Expression.Lambda<Func<int>> static method. The body of the expression is another expression Expression.Add() , which is taking two parameters which are constant expressions created using syntax Expression.Constant() .

The expression tree above is compiled into a lambda expression using the below statement.

Func<int> lambdaExpr = sumExpr.Compile()

In the last return statement the lambdaExpr is executed and the value is returned.

return lambdaExpr()

This is how a simple expression tree is created. There are different expressions like Parameter Expressions, Method Call Expressions etc. using which diverse expression trees can be created .

For further reading refer

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/

--

--