Mono.Linq.Expressions update 2
I just tagged the 1.2 version of Mono.Linq.Expressions, and pushed an updated nuget package.
Mono.Linq.Expressions is a utility library to complement the System.Linq.Expressions namespace, and works with .net 4.0 just as fine as it does with Mono. With a bit over 220 downloads of the nuget package, it's short of roughly 160,400 downloads to be the most downloaded nuget package : a stunning success to put it simply.
This post is the first of a short series to detail what's awesome and new in this version.
Extension methods for a fluent construction of expression trees.
Have you been using the expression tree API to build a representation of code at runtime ? If so you're familiar with the Expression class, and it's load of factory methods.
You're also familiar with this kind of code:
var user = Expression.Parameter(typeof (User), "user");
var isFemaleUserOver18 = Expression.Lambda<Func<User, bool>>(
Expression.AndAlso(
Expression.GreaterThanOrEqual(
Expression.Property(user, "Age"),
Expression.Constant(18)),
Expression.Equal(
Expression.Property(user, "Gender"),
Expression.Constant(Gender.Female))), user);
If you take some time to parse this code, the intent is to create an expression tree similar to the one the compiler would emit if you were to write:
Expression<Func<User, bool>> isFemaleUserOver18 =
user => user.Age >= 18 && user.Gender == Gender.Female;
Mono.Linq.Expressions 1.2 contains a code generated series of extension methods to simplify the manual construction of expression trees by fluently chaining the invocations. This allows you to write instead:
var user = typeof (User).Parameter("user");
var isFemaleUserOver18 = Expression.Lambda<Func<User, bool>>(
user.Property("Age").GreaterThanOrEqual(18.Constant())
.AndAlso(
user.Property("Gender").Equal(Gender.Female.Constant())), user);
Not only is the code shorter, but it's also easier on the eyes, and easier to comprehend. Using this, almost the factory methods calls to the Expression class can be written fluently.
Trackbacks
Use the following link to trackback from your own site:
http://evain.net/blog/articles/trackback/809
-
Interesting Finds: January 12, 2012
Hi Jb,
have look at this fluent API idea. I guess it would be useful in case of expression trees too.
http://zamboch.blogspot.com/2011/12/fluentator-generate-fluent-api-for-your.html
Pavel
Nice !