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(
If we print “e” directly to the console we will get the equation in infix notation:
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).
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.
Now, of course, this is an extremely simple example but you see the potential of the API.