Usage of '&' versus '&&'

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

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.


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.

Tags:

C#