V4Vendetta
V4Vendetta

Reputation: 38200

Usage of '&' versus '&&'

I came across this:

bool Isvalid = isValid & CheckSomething()

bool Isvalid = isValid && CheckSomething()

The second case could be a scenario for short circuiting.

So can't we always use just & instead of &&?

Upvotes: 95

Views: 125191

Answers (4)

Pleun
Pleun

Reputation: 8920

I believe you are missing something. In the second scenario CheckSomething is not evaluated if isValid is false

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary

Upvotes: 8

opiswahn
opiswahn

Reputation: 465

In && the second expression is only evaluated if the first one is true.

And & is just a way to guarantee that both expressions are evaluated, like true & true = true, true & false = false etc.

Upvotes: 17

adjan
adjan

Reputation: 13652

C# has two types of logical conjunction (AND) operators for bool:

  1. x & y Logical AND

    • Results in true only if x and y evaluate to true
    • Evaluates both x and y.
  2. x && y Conditional Logical AND

    • Results in true only if x and y evaluate to true
    • Evaluates x first, and if x evaluates to false, it returns false immediately without evaluating y (short-circuiting)

So if you rely on both x and y being evaluated you can use the & operator, although it is rarely used and harder to read because the side-effect is not always clear to the reader.

Note: The binary & operator also exists for integer types (int, long, etc.) where it performs bitwise logical AND.

Upvotes: 58

Talljoe
Talljoe

Reputation: 14827

& is a bitwise AND, meaning that it works at the bit level. && is a logical AND, meaning that it works at the boolean (true/false) level. Logical AND uses short-circuiting (if the first part is false, there's no use checking the second part) to prevent running excess code, whereas bitwise AND needs to operate on every bit to determine the result.

You should use logical AND (&&) because that's what you want, whereas & could potentially do the wrong thing. However, you would need to run the second method separately if you wanted to evaluate its side effects:

var check = CheckSomething();
bool IsValid = isValid && check;

Upvotes: 105

Related Questions