I am (still) learning C# - and I thought I understood the difference between &
& &&
as well as |
& ||
The difference will be less apparent in booleans; bitwise operators are primarily for numbers, whereas logical operators are primarily for booleans. In a bitwise operation (e.g., &), the operation is performed for each bit. In a logical operation (e.g., &&), the operation is performed for the entire result.
For example, the bitwise & of 11 (1011 in binary) and 2 (10 in binary) would be computed as such:
1011
& 0010
______
0010
which is 2.
There is an additional consideration in how the two types of operators are executed. When using a bitwise operator, the expressions on either side of the operator are first executed, and then the operation is performed. When using a logical operator, however, the expression on the left side of the operator is performed first, and the right side may be neglected if it will not change the result.
For example, when I execute (false expression) && (true expression)
, the true expression is never evaluated. Likewise with (true expression) || (false expression)
. This is referred to as short-circuit evaluation