Are LINQ expression trees proper trees, as in, graphs (directed or not, wikipedia does not seem too agree) without cycles? What is the root of an expression tree from the following C# expression?
(string s) => s.Length
The expression tree looks like this, with “->” denoting the name of the property of the node the other node is accessible through.
->Parameters[0]
Lambda---------Parameter(string s)
\ /
\->Body /->Expression
\ /
Member(Length)
When using ExpressionVisitor to visit the LambdaExpression, the ParameterExpression is visited twice. Is there a way to use the ExpressionVisitor to visit the LambdaExpression so that all the nodes are visited exactly once, and in a specific, well-known order (pre-order, in-order, post-order etc.)?
Sort of, yes. The actual “trunk” (if you will) of a
LambdaExpressionis the.Body; the parameters are necessary metadata about the structure of the tree (and what it needs), but.Parametersat the top (your dotted line) isn’t really part of the tree’s functional graph – it is only when those nodes are used later in the actual body of the tree that they are interesting, as value substitutions.The
ParameterExpressionbeing visited twice is essential, so that it is possible for someone to swap the parameters if they wanted – for example, to build an entire newLambdaExpressionwith the same number of parameters, but different parameter instances (maybe changing the type).The order will be fairly stable, but should be considered an implementation detail. For example, given a node such as
Add(A,B), it should make no semantic difference whether I visit thatA-first vsB-first.