BT

Edit Expression Trees with MetaLinq

by Jonathan Allen on Jun 14, 2007 |

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.

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT