Compartir a través de


&& 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 may be). 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, observe that the expression using && evaluates only the first operand.

// cs_operator_logical_and.cs
using System;
class MainClass
{
   static bool Method1()
   {
      Console.WriteLine("Method1 called");
      return false;
   }

   static bool Method2()
   {
      Console.WriteLine("Method2 called");
      return true;
   }

   static void Main()
   {
      Console.WriteLine("regular AND:");
      Console.WriteLine("result is {0}", Method1() & Method2());
      Console.WriteLine("short-circuit AND:");
      Console.WriteLine("result is {0}", Method1() && Method2());
   }
}

Output

regular AND:
Method1 called
Method2 called
result is False
short-circuit AND:
Method1 called
result is False

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 7.11.2 User-defined conditional logical operators

See Also

Reference

C# Operators

Concepts

C# Programming Guide

Other Resources

C# Reference