R – Declaratively build expression-tree rooted in a node of any type

expression-treeslambda

MSDN say:

The compiler can also build an
expression tree for you. A
compiler-generated expression tree is
always rooted in a node of type
Expression<TDelegate>; that is, its
root node represents a lambda
expression.

But what if I want to build an expression tree rooted in a node of type MethodCallExpression, BinaryExpression, etc.? And don't want to do this manually.

Best Answer

The workaround is to declare 2 helper functions

public Expression GetBody(Expression<Action> lambda)
{
    return lambda.Body;
}

public Expression GetBody<TResult>(Expression<Func<TResult>> lambda)
{
    return lambda.Body;
}

Usage examples:

var e1 = (MethodCallExpression)GetBody(() => this.FunA());
var e2 = (ConstantExpression)GetBody(() => 4 + 5);
var e3 = (BinaryExpression)GetBody(() => a + b);
Related Topic