Expression Trees in Visual Studio 2010

Expression Trees in Visual Studio 2010

In Visual Studio 2010, the expression trees API was extended and added to the dynamic language runtime (DLR), so that language implementers can emit expression trees rather than MSIL. To support this new goal, control flow and assignment features were added to expression trees: loops, conditional blocks, try-catch blocks, and so on.

There is a catch: You cannot use these new features “an easy way”, by using lambda expressions syntax. You must use the expression trees API.

Create an expression tree by using API methods that were not available in Visual Studio 2008. One of these methods is Expression.Block, which enables the execution of several expressions sequentially, and this is exactly the method that I need for this example.

// Creating a parameter for an expression tree.

ParameterExpression param = Expression.Parameter(typeof(int), “arg”);

 

// Creating an expression for printing a constant string.

MethodCallExpression firstMethodCall = Expression.Call(

typeof(Console).GetMethod(“WriteLine”, new Type[] { typeof(String) }),

Expression.Constant(“Print arg:”)

);

 

// Creating an expression for printing a passed argument.

MethodCallExpression secondMethodCall = Expression.Call(

typeof(Console).GetMethod(“WriteLine”, new Type[] { typeof(int) }),

param

);

 

// Creating a block expression that combines two method calls.

BlockExpression block = Expression.Block(firstMethodCall, secondMethodCall);

 

// Compiling and invoking an expression tree.

Expression.Lambda<Action<int>>(

block,

new ParameterExpression[] { param }

).Compile()(10);

 

Although the expression trees API was extended, the way expression trees work with lambda expression syntax did not change. This means that LINQ queries in Visual Studio 2010 have the same features (and the same limitations) that they had in Visual Studio 2008.

But because of the new features, you can find more areas outside of LINQ where you can use expression trees.

Ebook Download
View all
Learn
View all