6

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

1 Answer 1

7

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)
    );
Sign up to request clarification or add additional context in comments.

5 Comments

Fixed a typo. Also, congrats on 100k, enjoy your swag when it arrives in 6-8 weeks!
@DavidG Thank you, HNY and coding!
Congrats Ivan, indeed an inspiration, keep it up
Thanks @MrinalKamboj, wish you the same.
thanks @Ivan Stoev. its working now! i forget setup the return parameter at begin of block definition : )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.