Expression Trees in C#

Hi Friends,

In this section, thought to talk about Expression Trees. In order to understand it, you need to know what delegates are first. At-least basic knowledge is required. Delegates are just pointers to a function which you can pass it around and save it to variable. Now, the easiest way to create a delegate in C# is either by Func<> or Action<>. Action is used when the method is void and Func is used, when method returns something.  For example, here I will be using below class for my expression tree.

Github Link:- https://github.com/rahulsahay19/Advanced-C-

Here, I just have one method and one property, that’s it. Let’s say, I would like to store “ReturnSomething” in a delegate. I will use Func here like shown below. Here, you can see that, I have access of both to method and its properties.

Therefore, here it created a pointer to the method means I created a delegate which calls this method with the required parameters. Now, I can save the same to a variable. This variable can be a normal variable, which I can pass it around, give it to another method. So, now my snippet will look like as shown below.

A simple delegate using Func or Action is basically a storage of method.We can save a method call to a variable. And, this variable can be used again as a method like shown below.

Here, I have passed the class as input to the func() method and it prints the following output.

I have received the same thing, what I am doing in that foo class. I can create another func for returning bool property like

Now, let’s say I am getting inputs like two parameters and output as one parameter. In that case, it would be something like this

Here, What I have done, I have created a method which takes two inputs and return the sum of that.

Note:- Last parameter of Func says the output type.

Action is also the same with one difference that it doesn’t return anything or it returns void. Same example can be written like

Now, let’s go ahead and discuss Expressions. At the high level, Expressions, will also look like Funcs but its very different from Func.

But, I can’t invoke Expressions like Func. And if you see the properties of expression here, you won’t find Invoke method here. Rather, you can see properties like NodeType, Body etc.

This also means expression trees are data structures representing code. It means we can extract information out of it. Expression Trees become very handy when you are writing Entity Framework code. Entity Framework internally takes all the queries and parses as expression trees like shown below. Here, we can’t iterate data directly as its not in memory, say its sitting somewhere in SQL Server. Hence, expression needs to be evaluated. Therefore, Entity Framework, needs to extract the information which is getting provided here and translate the same into native language of SQL. This is one of the objective of Expression Trees. You can analyze the code and traverse like tree structure.

At the same time, If I just try C# query like shown below, it will produce Func as Func can be directly handed over to iterables.

Now, the next question comes here, how to analyze the Expression Tree? We can analyze the tree with base expression. One point to note here, when we are examining expressions, we need to see what kind of Expression types we are analyzing. There are many C# expression types, which you can refer here. Basically, supported expression types are:

So, if you debug expression, it will list tree something like

And, if you see body of that, you will find something like as shown below. This means it only takes arguments which you passed in the class.

Now, let’s go ahead and see how to parse expression trees. Since, I will be parsing expressions. Hence, I will be doing the same with base Expression class itself. One point to note here, these kind of parsers help us to demystify expression trees very easily. This will also help us to debug expressions.

This also means, I can get further inside Expression body like shown below

Which also means that, we can call parser recursively like shown below.

Once, I execute the same, I can see both the expressions’ result like shown below. Now, let’s see how to compile expression trees ahead of time. Compiling expression trees is very straight forward, just with the keyword compile itself. With compilation, each expression can be compiled to actual code. With compilation, I will receive the Func, this expression holds. This is a very neat way of creating runtime methods and delegates, without knowing their types. Now, with compile, my code looks like this.

And, it will produce the same output, like shown below.

Expressions are usually fast. But only slow part is compile operation in Expression Tree. Hence, we should try to compile the expressions as less as possible but also cache them. This way, operations will be faster.

One more important point to note with Expressions can’t be compared. These will always return false although if you pass the same expression to it.

 Let’s see, how to create expression without writing explicitly.

We can create expressions from the base Expression itself. It provides tons of static methods to help us like shown below.

Below, in the snippet, I have formed Expression step by step.

And, if you see in the debugger, this will give the same result, what we have achieved with the previous one.

And, end-result will also be same like shown below.

With this, I would like to wrap this post. In the next post, we will delve further. Till then stay tuned and Happy Coding.

Github Link:- https://github.com/rahulsahay19/Advanced-C-

Thanks,
Rahul Sahay
Happy Coding

372 total views, 2 views today