Why is &&
preferable to &
and ||
preferable to |
?
I asked someone who's been programming for years and his explanation was:
For example, in if (bool1 && bool2 && bool3) { /*DoSomething*/ }
, bool1
has to be true for it to test bool2
which has to be true before moving on to bool3
, etc. If I'd used a single &
instead there is no order to the test even if all of them have to be true to progress to the next line, so why does it matter anyway?
Note: I'd like to point out that I'm the programming equivalent of a toddler and this is not a serious or urgent question. It's more a matter of understanding why things should be done a certain way as opposed to another.
In most cases, &&
and ||
are preferred over &
and |
because the former are short-circuited, meaning that the evaluation is canceled as soon as the result is clear.
Example:
if(CanExecute() && CanSave())
{
}
If CanExecute
returns false
, the complete expression will be false
, regardless of the return value of CanSave
. Because of this, CanSave
is not executed.
This is very handy in the following circumstance:
string value;
if(dict.TryGetValue(key, out value) && value.Contains("test"))
{
// Do Something
}
TryGetValue
returns false
if the supplied key is not found in the dictionary. Because of the short-circuiting nature of &&
, value.Contains("test")
is only executed, when TryGetValue
returns true
and thus value
is not null
. If you would use the bitwise AND operator &
instead, you would get a NullReferenceException
if the key is not found in the dictionary, because the second part of the expression is executed in any case.
A similar but simpler example of this is the following code (as mentioned by TJHeuvel):
if(op != null && op.CanExecute())
{
// Do Something
}
CanExecute
is only executed if op
is not null
. If op
is null
, the first part of the expression (op != null
) evaluates to false
and the evaluation of the rest (op.CanExecute()
) is skipped.
Apart from this, technically, they are different, too:
&&
and ||
can only be used on bool
whereas &
and |
can be used on any integral type (bool
, int
, long
, sbyte
, ...), because they are bitwise operators. &
is the bitwise AND operator and |
is the bitwise OR operator.
To be very exact, in C#, those operators (&
, |
[and ^
]) are called "Logical operators" (see the C# spec, chapter 7.11). There are several implementations of these operators:
int
, uint
, long
and ulong
, chapter 7.11.1):&
is implement to compute the bitwise logical AND
etc.