Modifying Expression Trees
As I have started to play more with expression trees, I decided to learn how to modify expression trees. Well expression trees cannot be modified because they are read only. In order accomplish modification, you have to create a brand new tree, copy the existing expressions that are still valid, replacing the expression that you want changed. Below is an example that demonstrates changing a constant value from 1 to 3.
In the above example, I have a simple expression that adds 6, divides by 2 and adds one. All we are trying to accomplish is change the value of 1 to 3. I am first grabbing the body of the entire expression by calling Body on the expression and casting it to BinaryExpression. A BinaryExpression has a left and right operand. Looking at the graphic view of the expression, you can notice that in order to get to the value of 1, we need to access right side of the expression and cast it to a node type of ConstantExpression. Based on the diagram, I am accessing the right side of the body expression, casting it to ConstantExpression and printing the value of the expression. However as I mentioned earlier, expressions are read only, therefore cannot be changed. When I try to assign new value compiler does not allow. Here is the modified version of the code that replaces the constant expression with new expression.
In the above example I am creating a new expression and grabbing the left portion of the existing expression and replacing the right portion with the new constant expression I have created. You can confirm that the new expression has a value of 3 from the expression tree output printed on the screen.
Just to get a little more complex, I am going to change the value of 6 in the expression tree to 4. Below is an example that illustrates how to achieve the change.
In the above example, in order to get to the value of 6 I have to do two lefts on the binary expressions. Further more I have to recreate all the expressions that are above the expression that I want changed and rebuild the entire tree. From the output, you can confirm that our value of 6 has been updated to new value of 4.