Export (0) Print
Expand All

&& Operator (C# Reference)

The conditional-AND operator (&&) performs a logical-AND 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 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.

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.

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

Reference

Concepts

Other Resources

Show:
© 2014 Microsoft