Expression Tree Library Ignores Short Circuit Evaluation Concept

Please take a look at the following proof of concept:

private class Model
{
    public string Data { get; set; }
    public bool NonEmpty() { return Data.Length > 0; }
}

private static Func<Model, bool> Compile()
{
    var type = typeof(Model);
    var expr = Expression.Parameter(typeof(Model));

    var subarg1 = Expression.Property(expr, type.GetProperty("Data"));
    var subarg2 = Expression.Constant(null);
    var arg1 = Expression.NotEqual(subarg1, subarg2);

    var arg2 = Expression.Call(expr, type.GetMethod("NonEmpty"));

    var tree = Expression.And(arg1, arg2); // Data != null && NonEmpty()
    var func = Expression.Lambda<Func<Model, bool>>(tree, expr).Compile();
    return func;
}

var model = new Model {Data = null};
var standardTest = model.Data != null && model.NonEmpty(); // returns false
var exprTreeTest = Compile().Invoke(model); // throws null ref exception

Since the first operand evaluates to false, the result of the AND operation is false regardless of what the value of the second is. That is why the second operand should not be computed. While the C # compiler does this correctly, the expression library does not work.

How to fix my code to evaluate short circuit rating?

+4
source share
1 answer

Expression.Andrepresents the short circuit operator AND ( &).

Expression.AndAlsorepresents the short circuit operator AND ( &&).

+8
source

Source: https://habr.com/ru/post/1547977/


All Articles