views:

41

answers:

1

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.

A: 

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);
alex2k8