Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of (true && false || true) in C#?

If I have this equation:

    var x = (true && false || true)

Is that equivalent to:

    var x = ((true && false) || true)

or:

    var x = (true && (false || true))

And whats the logic behind this?

like image 409
Entity Avatar asked Nov 30 '22 08:11

Entity


2 Answers

AND wins over OR.

So it will be

var x = ((true && false) || true)

See Operator precedence and associativity.

like image 54
Aliostad Avatar answered Dec 02 '22 20:12

Aliostad


In boolean logic, "not" (!) is evaluated before "and" (&&) and "and" is evaluated before "or" (||). By using the double (&&) and the double (||), these operators will short circuit, which does not affect the logical outcome but it causes terms on the right hand side to not be evaluated if needed.

Thus

var x = (true && false || true) evaluates to false|| true which evaluates to true

and

var x = ((true && false) || true) evaluates to false || true which evaluates to true

and

var x = (true && (false || true)) evaluates to true && true which evaluates to true

like image 31
Jason Moore Avatar answered Dec 02 '22 21:12

Jason Moore