Working With Expression Trees
Now I am not going to be talking about expression trees in depth. I will be covering expression trees at basic level. The reason I started playing around with expression tree was not to write a provider but basically to be able express my intent at runtime. Linq is so much at compile time that sometimes it is not feasible for dynamic queries. This is where you can use expression trees that allows you define your intent based on runtime decisions.
System.Linq.Expression namespace contains all the classes that you would require to create expression trees. All the expression classes derive from an abstract class called Expression. Although there are quite a few classes that inherit from Expression class but the one that I have used more often is BinaryExpression. BinaryExpression is returned when you are performing arithmetic operation, to comparing, indexing and many others. Therefore in order to differentiate between these operations that return the same Expression class, you can make use of NodeType property on the expression class. NodeType enumeration has many values like Add,Multiply, Constant, Indexing etc. I will show how to use an expression starting with a simple Multiply operation. Here is an example of that.
In the above example, I start with two constant expressions and than add the two expressions to return a binary expression. Well at this point binary expression is of not of much use because we cannot execute it. What we really need is Expression<Delegate> class which has a compile method that convert an expression to a delegate. Once we have the delegate in hand we can execute the delegate in a usual fashion as we do in C#. Expression<Delegate> is a class that inherits from Lambda Expression that inherits from Expression class. Basically Expression<Delegate> is a strongly type intent that in our case says, we have an expression that has no parameters and returns an integer. In order to obtain that expression we pass our binary expression to the static method on Expression class called Lambda. Once we have the Expression of Func, we can call compile method to return a delegate which has no parameters and returns an int. Now all is left is to execute the code to get the output below.