Edit Expression Trees with MetaLinq
Expression trees are a powerful feature in any language. LINQ uses them under the covers to execute object queries, while DLINQ to SQL transforms them into SQL queries. Other people are using them to generate code on the fly. But like any other feature, there are design tradeoffs.
In order to better support things like query comprehension and function composition, expression trees are immutable. Libraries are guaranteed that once they have a reference to an expression tree, that expression tree will never change. Whole classes of bugs are eliminated by doing this, though it does make modified versions of an expression tree somewhat difficult.
Developers wishing to edit one have to manually build new expressions by copying existing ones. Aaron Erickson's MetaLinq allows developers to side-step this by providing a way to convert expression trees into mutable representations and back again.
MetaLinq does this with what Aaron calls an Editable Shadow. Developers create this shadow by passing an expression to the CreateEditableExpression method. When done making changes, they simply need to call ToExpression to get a usable expression tree again.
MetaLinq isn't the only way to edit expression trees. Jomo Fisher demonstrates a visitor pattern than will walk an expression tree, creating a new tree while swapping out specific nodes. While this technique is more complex conceptually, it does allow for some interesting search and replace techniques.
Eran Kinsbruner May 05, 2015