Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value in ExpressionTree

i'm trying to do for an expression tree and try to let it return a simple int value. but it not working anymore

        var method = typeof(Console).GetMethod("WriteLine", new Type[] {typeof(string)});

        var result = Expression.Variable(typeof(int));



        var block = Expression.Block(
            result,
          Expression.Assign(result,Expression.Constant(0)),
            Expression.IfThenElse(Expression.Constant(true),
                Expression.Block(Expression.Call(null, method, Expression.Constant("True")),
                    Expression.Assign(result, Expression.Constant(1))),
                Expression.Block(Expression.Call(null, method, Expression.Constant("False")), Expression.Assign(
                    result, Expression.Constant(0)
                ))),
            result
        );


        Expression.Lambda<Func<int>>(block).Compile()();
like image 809
Linkanyway Avatar asked Jan 08 '19 10:01

Linkanyway


People also ask

What is an expression that returns a value?

In programming languages expression is a unit of code which returns a value. A function call with return value is an expression - it returns value; an integer (or bool or address) literal is also an expression - it has the value of its integer type and so on. Expressions must be sequenced (separated) by a semicolon*

How do you solve expression tree?

We can evaluate an expression tree by applying the operator at the root to values obtained by recursively evaluating left and right subtrees. This can be easily done by traversing the expression tree using postorder traversal. The algorithm can be implemented as follows in C++, Java, and Python: C++

How does an expression tree work?

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y . You can compile and run code represented by expression trees.


1 Answers

The problem is not with returning a vaue from the block (you are doing it correctly), but the out of scope variable due to the used wrong Expression.Block method overload.

Variable expressions like your result must be passed to the block expression using some of the overloads with IEnumerable<ParameterExpression> variables argument, for instance

    var block = Expression.Block(
        new ParameterExpression[] { result },
        //... (the rest of the sample code unchanged)
    );
like image 198
Ivan Stoev Avatar answered Sep 28 '22 03:09

Ivan Stoev