Sunday, August 29, 2010

Expression trees are immutable

Expression trees are immutable, which means that they cannot be modified directly. To change an expression tree, you must create a copy of an existing expression tree and when you create the copy, make the required changes

Mutable Trees :-LINQ to SQL has an internal tree structure that’s mutable—and immutable trees like expression trees from the System.Linq.Expression namespace.

Discussion of the sorts of problems that can arise with mutable classes. Another advantage of immutable trees is that you can effectively duplicate them just by reference assignment.

Sample:-

Expression<Func<int, int>> f = (n => 1 - n);

Expression<Func<int, int>> g = f;

f = MyRewriteFunction(f);

Here, the variable ‘g’ keeps the original expression tree value while ‘f’ is rewritten with a new value.
Notice that this is a very fast reference copy. Without the immutability guarantee you would have to physically copy the tree to get the same guarantee

(http://blogs.msdn.com/b/jomo_fisher/archive/2007/05/23/dealing-with-linq-s-immutable-expression-trees.aspx)

No comments: