Compartir a través de


|| Operator (C# Reference) 

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

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.

Example

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

// cs_operator_short_circuit_OR.cs
using System;
class MainClass
{
    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());
    }
}

Output

regular OR:
Method1 called
Method2 called
result is True
short-circuit OR:
Method1 called
result is True

See Also

Reference

C# Operators

Concepts

C# Programming Guide

Other Resources

C# Reference