Export (0) Print
Expand All

&& Operator

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

expr1 && expr2


An expression.
An expression.


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 (see 7.11.2 User-defined conditional logical operators).


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

// cs_operator_logical_and.cs
using System;
class Test 
   static bool fn1() 
      Console.WriteLine("fn1 called");
      return false;

   static bool fn2() 
      Console.WriteLine("fn2 called");
      return true;

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


regular AND:
fn1 called
fn2 called
result is False
short-circuit AND:
fn1 called
result is False

See Also

C# Operators | 7.11 Conditional logical operators

© 2015 Microsoft