Export (0) Print
Expand All

|| Operator

The conditional-OR operator (||) performs a logical-OR of its bool operands, but only evaluates its second operand if necessary.

expr1 || expr2

Where:

expr1
An expression.
expr2
An expression.

Remarks

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 7.11.2 User-defined conditional logical operators).

Example

In the following example, observe that the expression using || evaluates only the first operand.

// cs_operator_short_circuit_OR.cs
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());
   }
}

Output

regular OR:
fn1 called
fn2 called
result is True
short-circuit OR:
fn1 called
result is True

See Also

C# Operators | 7.11 Conditional logical operators

Show:
© 2014 Microsoft