An example of it in use would be...
if (temp < 30 || temp > 90) { MessageBox.Show("Error"); }
What do two pipes (||) together mean?
An example of it in use would be...
if (temp < 30 || temp > 90) { MessageBox.Show("Error"); }
What do two pipes (||) together mean?
One pipe is a logical OR operator which always evaluates both operands.
Two pipes is short-circuiting logical OR operator, which only evaluates the second operand if the first one is false
. This is especially useful if the second operand is a heavy function that you don't want to evaluate unnecessarily or it is something that can throw an exception, e.g.:
if(myList == null || myList.Count == 0){
//do something
}
In this example, if myList
is null
, the second operand is never evaluated. If we use one pipe instead, the second operand will be evaluated and will throw an exception because myList
is null
.
A pipe |
in C# (and many other languages [except when a single pipe is used as a bitwise logical operator, such as in Java]) is the logical operator OR.
The double pipe ||
is shortcut OR. It means that if the first is true, then the operation will automatically quit, because one condition is already true. Therefore, OR must be true. (A single |
, therefore, means that it will check all conditions first before evaluating, which is slower and usually not useful).
In your example:
if (temp < 30 || temp > 90) { MessageBox.Show("Error"); }
temp < 30
: first condition||
: logical ORtemp > 90
: second conditionThis means, if (the first condition) OR (the second condition) is true, then show "Error".