Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Further Exploring the .NET Expressions API

0.00/5 (No votes)
4 Aug 2010CPOL2 min read 8.7K  
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 lambdas) 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 that I scan the new equation left to right, I will create the appropriate expression construct.

C#
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 lambda expression. Since the function is parameterless, I will use Func<int> as the delegate type.

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

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

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)