Ok, so I\'ve read about this a number of times, but I\'m yet to hear a clear, easy to understand (and memorable) way to learn the difference between:
if (x |
Strongly recommend to read this article from Dotnet Mob
For OR logical operation if any of it's operand is evaluated to true then whole expression is evaluated to true
this is what || Operator does - it skips the remaining evaluation when it found a true. While | Operator evaluate it's complete operands to asses the value of whole expression.
if(true||Condition1())//it skip Condition1()'s evaluation
{
//code inside will be executed
}
if(true|Condition1())//evaluates Condition1(), but actually no need for that
{
//code inside will be executed
}
It is better to use Short Circuited version of Logical Operator Whether it is OR(||) or AND(&&) Operator.
int i=0;
if(false||(++i<10))//Now i=1
{
//Some Operations
}
if(true||(++i<10))//i remains same, ie 1
{}
This effect is called side effect, actually seen in right side of expression in short circuited logical operators
Reference : Short-circuit Evaluation in C#