What is the difference between logical and conditional AND, OR in C#?

Sahat Yalkabov picture Sahat Yalkabov · Jul 1, 2010 · Viewed 86.1k times · Source

Possible Duplicate:
What is the diffference between the | and || or operators?

Logical AND and OR:

(x & y)
(x | y)

Conditional AND and OR:

(x && y)
(x || y)

I've only known about conditional operands up to this point. I know what it does and how to apply it in if-statements. But what is the purpose of logical operands?

Answer

Cogwheel picture Cogwheel · Jul 1, 2010

I prefer to think of it as "bitwise vs. conditional" rather than "logical vs conditional" since the general concept of "logical" applies in both cases.

x & y    // bitwise AND, 0101 & 0011 = 0001
x | y    // bitwise OR,  0101 | 0011 = 0111

x && y   // true if both x and y are true
x || y   // true if either x or y are true

Edit

By popular demand, I should also mention that the arguments are evaluated differently. In the conditional version, if the result of the entire operation can be determined by the first argument, the second argument is not evaluated. This is called short-circuit evaluation. Bitwise operations have to evaluate both sides in order to compute the final value.

For example:

x.foo() && y.bar()

This will only call y.bar() if x.foo() evaluates to true. Conversely,

x.foo() || y.bar()

will only call y.bar() if x.foo() evaluates to false.