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);
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();
var exprTreeTest = Compile().Invoke(model);
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?
source
share