Further Exploring the .Net Expressions API

The .Net Expressions API (as a part of System.Linq.Expressions assembly) provides a vast set of functions that can be used to express mathematical expressions, which can be composed and executed (as lambas) at runtime. Expressions.Add, .Multiply, and .Subtract, are just some of the mathematical functions offered by the API that can be used to express large equations. And, conveniently, the API lends itself well to infix notation (expressions where the operators come before the operands; e.g. (+ * 4 5 6…in infix this would be written as (4 * 5) + 6).

Let’s convert (3 * 9) + 5  into a lambda using the Expressions API. The first thing I will do is express this equation in prefix notation: + * 3 9 5. So as I scan the new equation left to right I will create the appropriate expression construct.

Expression e = Expression.Add(
   Expression.Multiply(Expression.Constant(3), Expression.Constant(9),
         Expression.Constant(5)));

 

If we print “e” directly to the console we will get the equation in infix notation:

image

Notice I did not have to do anything special to “pretty print” the equation. I did not have to write a stack to hold all the variables used, I did not have to create a visitor to print the nodes of the tree…I let .Net handle that for me.

If we want to actually execute it we need to create a lamba expression. Since the function is paramaterless I will use Func<int>as the delegate type.

var fn = Expression.Lambda<Func<int>>(e).Compile();

This line of code creates a Lamba expression whose delegate is of type Func<int> (which simply means the delegate will return an int and has no parameters).

Console.WriteLine(fn().ToString());

Once the function is compiled it can be executed as if it were a conventional method call. Print the result to the console to get 32 as the answer to the equation.

 image

Now, of course, this is an extremely simple example but you see the potential of the API.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s