Expression Trees in C#

TodlyCodly
3 min readMar 30, 2023

--

Expression tree in C# is very useful language feature. Due to fact that most of time it is utilized by libraries and its definition is done using the same syntax as lambda expressions it is not fully explored.

Basic understanding

In simplest form expression tree is code in code:

Is represented :

What we can get from this expression is:

NodeType- Lambda

It represents addition — Add

It has two named parameters {x} & {y}

Most important aspect of Expression tree is fact that it is never run as code. To make it callable object one needs to compile and invoke:

Usage

Most important usage of Expression Tree is Entity Framework and ability to translate C# code to SQL.

But this is not only usage, most of developers is familiar with eg. Automapper and its ForMember methods utilize Expression Trees :

To show what we can do with Expression Tree I decided to prepare
Hello World! generator using Expression Trees:

Effect of this program is :

Block Generator

Block Generator is a class which has capability to :

  • Define Lambda Function Expression with Block Expression:

Block expression allows to execute multiple expressions during lambda execution:

(x,y) => {
expr1;
expr2;
etc..
}

Block Generator class contains two containers for variables and arguments:

There is additional set of extension methods to build Fluent API and reference variables by their names:

  • Define Parameters & Argument Expression
  • Define Assignment Expressions
  • Define Call Expression

Code repository

mes1234/ExpressionForest (github.com)

Conclusions

Expression Trees is very powerful feature in C#. Example I used was prepared for fun, but there is much more to Expression Trees than Entity Framework.

Building a dedicated DSL (domain specific language) is one of very interesting concepts to explore.

--

--

TodlyCodly

C# developer, who once was Pythonista and dreams of being Golang guy.