Building Expression Trees from Scratch

Just out of curiosity i decided to create expression trees from scratch instead of using lambda statements to get my expressions trees. In all my projects, I haven't really found any significant need to create expression trees from scratch. Most of the time lambda statements are sufficient for me to create any complex expressions. However to understand lambda expressions better, it think it is essential to comprehend, how compiler converts lambda statements to expression syntax. In the example below, I am going to create a very simple expression tree that takes two parameters, multiples both parameters and adds two it.

image

image 

In the above example, I am first creating a constant expression of type integer. Than I am creating two parameter expressions that my final expression needs. Both parameter expressions are defined as integer type. The third parameter in Expression.Parameter represents the alias that you will  use to refer to the parameter in the expression tree. Next I create my first expression which is simply a multiplication of the X and Y parameter. I obtain my final expression by adding the constant with multiplied expression. This is an example where I am combining two expression by using Add operand. Now in order to build my final expression I make use of Expression.Lambda static method that takes the body of the expression which we created earlier follow by the parameters needed by the expression trees.

From the output window, you can see that we have the same output which ever path we choose to create our lambda expressions from. However I think creating even a simple expression tree is a high learning curve. An example such as above which I think is fairly non trivial took me 45 minutes to write. I hope this small tutorial gave you in sight in how to build lambda expressions from scratch.

No Comments