Well, by now we all know how to abuse System.Reflection
to the point of absurdity, so now it’s time to start the abuse of System.Expressions
. The System.Expressions
namespace contains everything you need to build lambda expressions on the fly, then compile them at run time for use. One may ask “Why Bother?” Well my friend, the answer is Speed. If you are using reflection heavily in your projects, you are likely to get a nice speed boost by switching to Expressions. There is one detail to keep in mind though, that the actual compilation of expressions can take some time, so you will want to cache the result.
First off, let’s take a look at a simple lambda, and then try to build it dynamically. Say we want to grab the length of a string
:
Func<string, int> getStrLen = x => x.Length;
The lambda expression that we are assigning to the delegate has 2 main parts, the x
parameter, and the x.Length
property access. Let’s go ahead and create these two smaller expressions. Expressions use a factory pattern and can only be instantiated through static
methods of Expression, so here is the code to build those two parts:
var param = Expression.Parameter(typeof(string), "x");
var prop = Expression.Property(param, "Length");
Expression.Parameter
takes a Type
as the first parameter, which is the type of the parameter, and a string
as the second parameter which is only used when you .ToString()
the expression. Expression.Property
takes another Expression as the first parameter, in our case we are using the ParameterExpression
we created on the line before, but it can be a few other things like other PropertyExpressions
, ConstantExpressions
, CallExpressions
, etc. The second parameter of Expression.Property
is a string
, it is just the name of the property you want to get. All that is left to do now is to build the lambda expression itself, and compile it:
var lambda = Expression.Lambda<Func<string, int>>(prop, param);
Func<string, int> result = lambda.Compile();
Expression.Lambda
has both regular and generic versions, we want to use the generic because we want to be able to call it as directly as possible. The first parameter it takes is the body of the lambda, and in our case that is x.Length
, which is our prop variable. Every parameter after the first should be ParameterExpressions
representing parameters that you are passing to the lambda, and should match the order and number of the generic parameters on the delegate type that is used as the generic for Expression.Lambda
. The call to lambda.Compile()
is where the real magic happens, the library compiles our expression tree down to executable code. So, we've dynamically built the same lambda as we have assigned to getStrLen
. If you are looking for more proof, check lambda.ToString()
, which also comes in handy when you are trying to debug your expression building code. Alright, now let’s build a nice generic method using the same pieces as above, starting off with the method signature:
Func<T,R> BuildGetProperty<T, R>(string propName)
Our method will have two generic parameters, T
which is the type containing the property, and R
which is the type of the property, and one string
that will be the name of the property to get. The body of our method is going to be almost verbatim of what is outlined above, except that we are going to substitute our generic types and property name. The end result is:
public static Func<T,R> BuildGetProperty<T, R>(string propName)
{
var param = Expression.Parameter(typeof(T), "x");
var prop = Expression.Property(param, propName);
var lambda = Expression.Lambda<Func<T, R>>(prop, param);
return lambda.Compile();
}
So, we could replace our getStrLen
lambda above with:
var getStrLen = BuildGetProperty<string, int>("Length");
And to use it:
var len = getStrLen("woot");
Which would yield 4 as the result. I'll be covering more on Expressions in further posts, so stay tuned. Also, comments are more than welcome since this is my first post.