Combining Expression Trees
Today, I was working with expression trees and had the need to combine two expression trees. It appears that when you try to combine two expression trees, it doesn't work. Compiler raises an an exception and does not allow combining two expression trees. Instead you need to convert expression tree into delegate by compiling the expression tree and using the compiled delegate with the existing expression tree to get the new expression tree. Here is an example that C# compiler does not allow.
In the above example, compiler raises an error when I try to merge two expression trees, complaining variable is used like a method. Error is not very meaningful but essentially if you compile the square expression tree into delegate and than use it with squareplus2 expression tree, you get a new expression tree. Here is an updated example of merging two expression trees together.
In the above code, you will notice that I am first compiling my square expression tree to a delegate and than passing in the n parameter expected by the delegate. Later I am getting the ToString version of squareplus2 expression tree which simply prints the expression tree invocation to the output screen. In order to execute my expression tree, I have to first compile it therefore I am compiling my new expression tree, squareplus2 and than passing in the value of 4 to get the value for the entire expression. From the result in the output screen, you can see that our new expression combines both expression to get the correct value.