8

why this is true:

(true | false & false)

and this is false:

(true | false && false)

in my mind should be the oposite..

Rodolfo
  • 181
  • 1
  • 1
  • 9
  • 6
    `|` and `&` are bitwise operators (that happen to be defined for bools as well) - use `||` and `&&` for logical operations including short-curcuiting. –  Feb 11 '11 at 11:38
  • That's the reason why I always explicitly add braces in such situations ;-) – Lucero Feb 11 '11 at 11:39
  • @delnan: Terminology nitpick: `|` and `&` are defined for integral types and for bool. For integral types they are bitwise operators; for bool they are logical operators without short-circuiting. – R. Martinho Fernandes Feb 11 '11 at 11:47
  • @Martinho: Well, assuming the definition `true = 1` and `false = 0`, both work ;) But point taken. –  Feb 11 '11 at 11:50

3 Answers3

15

They bind as:

true | (false & false)  // true

and

(true | false) && false  // false

I would avoid writing code which relies on these rules though - it's obviously unclear to the reader :)

For reference, see section 7.3.1 of the C# 4 language specification, which shows & having higher precedence than | (hence the first result) and | having higher precedence than && (hence the second result).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

This is because of operator precedence here

DaeMoohn
  • 1,087
  • 13
  • 27
3

& has priority to | which has priority to &&, so your expressions are evaluated as

(true | (false & false)) = (true | false) = true

and

((true | false) && false) = (true && false) = false

See the reference of C# operators containing there precedence for more information.

Sören
  • 2,661
  • 2
  • 19
  • 22