Usage of '&' versus '&&'

C#

C# Problem Overview


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 &&?

C# Solutions


Solution 1 - C#

& 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;

Solution 2 - C#

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.

Solution 3 - C#

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

And & is just a way to concatenate the two expressions, like true & true = true, true & false = false etc.

Solution 4 - C#

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.

http://msdn.microsoft.com/en-us/library/2a723cdk(v=vs.71).aspx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionV4VendettaView Question on Stackoverflow
Solution 1 - C#TalljoeView Answer on Stackoverflow
Solution 2 - C#adjanView Answer on Stackoverflow
Solution 3 - C#opiswahnView Answer on Stackoverflow
Solution 4 - C#PleunView Answer on Stackoverflow