|| Operator (C# Reference)

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


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.


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

class ConditionalOr
    static bool Method1()
        Console.WriteLine("Method1 called");
        return true;

    static bool Method2()
        Console.WriteLine("Method2 called");
        return false;

    static void Main()
        Console.WriteLine("regular OR:");
        Console.WriteLine("result is {0}", Method1() | Method2());
        Console.WriteLine("short-circuit OR:");
        Console.WriteLine("result is {0}", Method1() || Method2());
regular OR:
Method1 called
Method2 called
result is True
short-circuit OR:
Method1 called
result is True

See Also


C# Programming Guide


C# Operators

Other Resources

C# Reference

Change History




October 2008

Corrected code example.

Customer feedback.