Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C#
C# Reference
C# Operators
 && Operator

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
C# Language Reference
&& 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 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.

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

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

  • 7.11.2 User-defined conditional logical operators

Reference

C# Operators

Concepts

C# Programming Guide

Other Resources

C# Reference

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker