The conditional-OR operator (&&) performs a logical-OR of its bool operands, but only evaluates its second operand if necessary. That is, the operation
x || y
corresponds to the operation
x | y
except that if x
is true
, y
is not evaluated (because the result of the OR operation is true
no matter what the value of y
might be). This is known as "short-circuit" evaluation.
The conditional-OR operator cannot be overloaded, but overloads of the regular logical operators and operators true and false are, with certain restrictions, also considered overloads of the conditional logical operators (see CLR 7.11.2 User-defined conditional logical operators).
In the following example, observe that the expression using || evaluates only the first operand.
using System; class Test { static bool fn1() { Console.WriteLine("fn1 called"); return true; } static bool fn2() { Console.WriteLine("fn2 called"); return false; } public static void Main() { Console.WriteLine("regular OR:"); Console.WriteLine("result is {0}", fn1() | fn2()); Console.WriteLine("short-circuit OR:"); Console.WriteLine("result is {0}", fn1() || fn2()); } }
regular OR: fn1 called fn2 called result is True short-circuit OR: fn1 called result is True
C# Operators | CLR 7.11 Conditional logical operators