Exploring ExpressionTrees

Lomo, by Niek Beck

What is an Expression Tree?

Before we can understand a .NET ExpressionTree first we need to cover the concept of delegates in .NET. I’m going to assume a basic level of understanding here, and so will only quickly cover this concept. A delegate is a .NET object that represents a method – usually a small one. Most commonly, we see these as Func’s or Action’s, and we commonly use them in lambda expressions.

We can write our own small delegate example as:

Func<int, bool> IsEven = (x => x % 2 == 0);

The above is a very simple Func that accepts an int as a parameter and returns a bool. We could use it like:

var list = new[] { 1, 2, 3, 4, 5 };
var evens = list.Where(x => IsEven(x)); // returns { 2, 4 }

We use these delegate classes when we want to execute a small piece of code – and when we only care about the actual result (which is really most programmers, most of the time).

Got it – so again, what is an ExpressionTree?

An ExpressionTree is essentially the raw (uncompiled) version of a delegate. In code they often look very similar to delegates, for example I could have:

ExpressionTree<Func<int, bool>> IsOdd = (x => x % 2 != 0);

However unlike delegate’s I cannot directly use them, as I did above. If I wanted to use one I’d firstly need to compile it:

Func<int, bool> IsOddFunc = IsOdd.Compile();
var odds = list.Where(x => IsOddFunc(x));

What on earth is the point of that??

Sometimes, we want to write code that isn’t just focused on a result – we want to capture additional information or context behind the result. ExpressionTree’s allow us to pull apart the statement that was provided, and perform a whole range of actions on it.

Because it is raw – and uncompiled – we can pull apart the parameters to the function, and even jump through the actual expression itself.

This sounds quite abstract – but in my next post or two I’m going to do this to demonstrate some practical applications of this – and why this is so useful.

As a final note (and for some further reading) .NET supports a very wide range of delegates. The same goes for ExpressionTree’s, and you can get an idea of the types of ExpressionTree’s we can produce by reading through the list supported here:

http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx

 

Photo Credit: Niek Beck

Leave a Reply to Mocking data sets with ExpressionTrees Cancel reply

Your email address will not be published. Required fields are marked *