共用方式為


&& Operator (C# Reference)

The conditional-AND operator (&&) performs a logical-AND 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 false, y is not evaluated, because the result of the AND operation is false no matter what the value of y is. This is known as "short-circuit" evaluation.

The conditional-AND 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, the conditional expression in the second if statement evaluates only the first operand because the operand returns false.

class LogicalAnd
{
    static void Main()
    {
        // Each method displays a message and returns a Boolean value.  
        // Method1 returns false and Method2 returns true. When & is used, 
        // both methods are called. 
        Console.WriteLine("Regular AND:");
        if (Method1() & Method2())
            Console.WriteLine("Both methods returned true.");
        else
            Console.WriteLine("At least one of the methods returned false.");

        // When && is used, after Method1 returns false, Method2 is  
        // not called.
        Console.WriteLine("\nShort-circuit AND:");
        if (Method1() && Method2())
            Console.WriteLine("Both methods returned true.");
        else
            Console.WriteLine("At least one of the methods returned false.");
    }

    static bool Method1()
    {
        Console.WriteLine("Method1 called.");
        return false;
    }

    static bool Method2()
    {
        Console.WriteLine("Method2 called.");
        return true;
    }
}
// Output: 
// Regular AND: 
// Method1 called. 
// Method2 called. 
// At least one of the methods returned false. 

// Short-circuit AND: 
// Method1 called. 
// At least one of the methods returned false.

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

C# Operators

Concepts

C# Programming Guide

Other Resources

C# Reference