Subtree substitution thanks to microsoft ExpressionVisitor

Previous part: Part1, Part2, Part3.

One of the most important feature of the microsoft ExpressionVisitor I’ve told you before is the ability to substitute expression. Let’s for example see how the VisitBinary is implemented.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 1 protected virtual Expression VisitBinary(BinaryExpression b)
 2 {
 3     Expression left = this.Visit(b.Left);
 4     Expression right = this.Visit(b.Right);
 5     Expression conversion = b.Conversion == null ? null : this.Visit(b.Conversion);
 6     if (left != b.Left || right != b.Right || conversion != b.Conversion)
 7     {
 8         if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null)
 9             return Expression.Coalesce(left, right, conversion as LambdaExpression);
10         else
11             return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
12     }
13     return b;
14 }

As you can notice, in the line 6 the code is checking if the subtree returned from the left or right branch evaluation are different from the original one, if yes it simply substitute the expression. This is important because we can build visitor that actually replaces part of the tree making traversal simplier. One of the most interesing application is given in this looooong tutorial. Here the author use extensively this feature to build a mini linq to sql provider.

The rule of thumb is, it is not necessary to walk the Expression Tree only one time, it is possibile to traverse it multiple times, each time modify to deal in each pass with a simplier tree.

alk.