Home > View Post

Lambda and Expression Trees

I'd been working on this post already when Scott kindly posted about Ukadc.Diagnostics in the Weekly Source Code 27: Suck Less Libraries.

His favourite part of the library came as a surprise: "However, the gem I found while reading the source wasn't actually directly related to the library's purpose. Rather, it's the implementation of a Fast Property Getter.". This is where we use Dynamic Methods and Reflection Emit to have the "flexibility of Reflection but near-native speeds".

So what does this have to do with Lambda Expressions? Funny you ask.

Following my two previous posts Delegates and Lambda and Func and Action I wanted to start talking about Expression Trees.

In the next post on this subject we'll quickly look at what makes Expression Trees really interesting but in this post, as an introduction, I wanted to show how we can use Expression Trees to generate Lambda Expressions at runtime. I won't hang about - let's get straight into an example:

ParameterExpression paramA = Expression.Parameter(typeof(Int32), "a");
ParameterExpression paramB = Expression.Parameter(typeof(Int32), "b");
BinaryExpression add = Expression.Add(paramA, paramB);
Expression<Func<int, int, int>> exp = Expression.Lambda<Func<int, int, int>>(add, paramA, paramB);

Console.WriteLine("Expression: {0}", exp);

Func<int, int, int> lambda = exp.Compile();

Console.WriteLine("Example: {0}", lambda(4, 5));

And here's the output of our console application:

Runtime generated Lambda

As you can see, we've created a lambda expression at runtime that looks like this:

(a, b) => (a + b)

And we even compile and execute the lambda, making it add 4 and 5 to give the output of 9. Very clever. But useless.

However, whilst another way of creating code at runtime wasn't the motivation behind adding Expression Trees to .NET (we already have DynamicMethods, Reflection Emit and CodeDom) it can be very useful. One application would be to replace all the horrific IL.Emit calls in Ukadc.Diagnostic's FastPropertyGetter. Here's the current FastPropertyGetter using DynamicMethod and IL.Emit - the IL.Emit calls are highlighted.

FastPropertyGetter with IL.Emit

And here's the same class using Expression Trees to describe the method body:

FastPropertyGetter with Lambda

The interesting bit looks like this:

var param = Expression.Parameter(typeof(object), "source");
var source = Expression.Convert(param, type);
var get = Expression.MakeMemberAccess(source, propertyInfo);
var convert = Expression.Convert(get, typeof(object));
var lambda = Expression.Lambda<Func<object, object>>(convert, param);

GDDelegate = lambda.Compile();

Ping me if you'd like the full source.

Sadly, I won't be able to implement this in Ukadc.Diagnostics because we want to support .NET 2 where we mightn't have access to all this juicy lambda stuff.

Tags: .NET

Josh Post By Josh Twist
1:52 AM
21 May 2008

» Next Post: Propagating the ActivityId to a WCF service
« Previous Post: Updated Silverlight Uploader for SL2 Beta 1

Comments are closed for this post.

Posted by Rupert Benbrook @ 23 May 2008 1:03 AM
I might be wrong, but have you seen LINQBridge (http://www.albahari.com/nutshell/linqbridge.html)?Reading the blurb, it looks like it may let you use LINQ in a .NET 2.0 environment. Worth a look anyway!

Posted by Josh @ 23 May 2008 1:32 AM
Cheers Rupert, looks interesting. It looks like it would support LINQ (L2O) but I can't see how it would give you support for Expression Trees in .NET 2. Looks very cool nonetheless.

Posted by Darren Kopp @ 30 Jun 2008 12:47 PM
Oh man, i sure wish i would have found this page earlier, then i wouldn't have had to have figured out this solution on my own. Looks like you and I had the same idea, just at different times / places.


Posted by josh @ 30 Jun 2008 12:49 PM

I doubt I was the first either :)

Posted by Bkak @ 06 Oct 2009 1:27 AM
Hello josh,

I never seem to have understood Expression Trees. I do not understand its benefits other than complicating the normal code. Anyways, i was interested in knowing if I can do some serious stuff with Expression Trees.

My requirement is to construct a method at runtime. I will be having the logic to be put into that method, i want to compile it at runtime. It should take parameters from the current context and return some value to current context. The logic might be dealing with these parameters only but shall be having for, while loops, variable declaration and those stuff. This is possible through codeDom but that slows down the process.

I would highly appreciate if you could show me a way to do it using Dynamic methods/Expression Trees/Lambda Expressions.


© 2005 - 2022 Josh Twist - All Rights Reserved.