Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Expression.And represents "&" but not "&&"


I have the following class:

public class Test
{
    public string Text { get; set; }
    public int Number { get; set; }
}

And I'm creating and Expression tree of type Expression<Func<Test, bool>> on this class. When I do it like this:

Expression<Func<Test, bool>> predicate1 = x => x.Text.Length > 5 && x.Number > 0;

I get the following debug view:

.Lambda #Lambda1<System.Func`2[NHLinqTest.Test,System.Boolean]>(NHLinqTest.Test $x) {
    ($x.Text).Length > 5 && $x.Number > 0
}

note: there's a && for and-operation.
When I do it like this:

    var y = Expression.Parameter(typeof(Test));

    var predicate2 = Expression.And(
        Expression.GreaterThan(
            Expression.Property(Expression.Property(y, "Text"), "Length"),
            Expression.Constant(5)),
    Expression.GreaterThan(
        Expression.Property(y, "Number"),
            Expression.Constant(0)));

I get the following debug view:

($var1.Text).Length > 5 & $var1.Number > 0

Note: there's & for and-operation. Why do I get & in the second case? How to modify predicate2 to get && instead of &?
Thanks in advance!

like image 884
StuffHappens Avatar asked Jan 18 '11 11:01

StuffHappens


3 Answers

Because it is & - i.e. bitwise / non-short-circuiting "and". For && you want Expression.AndAlso.

See also Expression.Or (|) vs Expression.OrElse (||).

Also, note that Expression != C# - it is language independent, so you might also see some cases where you don't get back (visually) what you would expect from C#.

like image 59
Marc Gravell Avatar answered Oct 18 '22 15:10

Marc Gravell


Compare Expression.And:

Creates a BinaryExpression that represents a bitwise AND operation.

and Expression.AndAlso:

Creates a BinaryExpression that represents a conditional AND operation that evaluates the second operand only if the first operand evaluates to true.

And then compare that to your knowledge of the & and && operators.

like image 40
Damien_The_Unbeliever Avatar answered Oct 18 '22 16:10

Damien_The_Unbeliever


The "&" operator and Expression.And represent a bitwise and. The "&&" operator and Expression.AndAlso represent a logical (and short-cutting) and operator.

like image 34
BlueMonkMN Avatar answered Oct 18 '22 17:10

BlueMonkMN