C# 3.0 Enhancements: Expression Trees

C# 3.0 Enhancements: Expression Trees

  • Comments 1

Expression Tree is the feature which enables us to write function which can be complied on-demand basis. It stores the function in form of structured data rather than executable code. Since this is structured we can easily iterate through it anytime. This is easier than finding something in IL.

 

Let’s suppose if you have code like

 

Func<int, int> f = x => x * 5;

Console.WriteLine(f(30));

 

and you execute it. This will execute normally.

 

But what if you want to store the whole function body in IL and compile as and when required. Then the above code look little different.

 

Expression<Func<int, int>> e = x => x * 5;

 

Now you cannot execute expression like function. But you can see the body of the expression in Expression Tree Visualizer. To use Expression you need to use the namespace System.Linq.Expressions

 

So if you use the code like

 

Console.WriteLine(e);

 

The output will look like, x => (x * 5) instead of some kind of perfect integer values. Now if you want to use the function written there in Expression Tree you need little different approach,

 

var f = e.Compile();

Console.WriteLine(f(30));

 

Compile statement will compile the IL code and your function will be ready for execution.

 

If you want to write your own Expression instead of using the Expression <> to convert the delegate to function call, .NET allows us to do that. The Expression representation of the above f = x => x * 5; will look like

 

ParameterExpression x = Expression.Parameter(typeof(int), "x");

Expression body = Expression.Multiply(x, Expression.Constant(5));

Expression<Func<int, int>> e = Expression.Lambda<Func<int, int>>(body, x);

 

 

 

This happens exactly when you use SQL statement and execute it SQL Server database. Internally it creates functions and send to the compiler, then compiler compiles the code during the execution. Various rules engine like BizTalk uses this concept.

 

Now if you put a break point on e and hover over it during debug you can get the Expression Tree out of it.

 

 

I am loving itJ

 

Namoskar!!!

 

 

Leave a Comment
  • Please add 7 and 1 and type the answer here:
  • Post
  • Hi,

    great. Where can I get the viewer?

Page 1 of 1 (1 items)