Search code examples
c#.netlinqexpressionexpression-trees

Different ways to parse / visit Expressions when traversing


I have a basic question about parsing expression trees.

Is there a difference between using if statements to determine the NodeType of an expression, and handling it accordingly, versus dispatching the expression do a different Visitor method?

Also is this even the correct way to dispatch:

    protected override Expression VisitMember(MemberExpression m)
    {
        if (m.Expression.NodeType == ExpressionType.Constant)
        {
             Expression e = (m.Expression as ConstantExpression); 

             this.Visit(e); // dispatches to VisitConstant() ?
        }

    }

Versus:

    protected override Expression VisitMember(MemberExpression m)
    {
        if (m.Expression.NodeType == ExpressionType.Constant)
        {
             //specific code to handle constant
        }
    }

By the way this is in reference to parsing the following:

dbContext.Products.Where(x => x.ID == user.ProductID).AsEnumerable()
// user.FooID is 'MemberExpression' 

What exactly is the relationship between NodeType and simply the Type of the Expression? Ive noticed for instance there are are NodeTypes which dont seem to have overridable visitor methods, is that correct?


Solution

  • Some expression types, like MemberInit have a one-to-one correspondence between the class and the associated ExpressionType enumerated value, while with others the class is more generic and relates to more than one ExpressionType, like with BinaryExpression (can be Add,Divide, etc.).