The short-circuit operators : Short Circuit Operators « Operator « C# / CSharp Tutorial

Home
C# / CSharp Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statement
5.String
6.struct
7.Class
8.Operator Overload
9.delegate
10.Attribute
11.Data Structure
12.Assembly
13.Date Time
14.Development
15.File Directory Stream
16.Preprocessing Directives
17.Regular Expression
18.Generic
19.Reflection
20.Thread
21.I18N Internationalization
22.LINQ
23.GUI Windows Forms
24.Windows Presentation Foundation
25.Windows Communication Foundation
26.Workflow
27.2D
28.Design Patterns
29.Windows
30.XML
31.XML LINQ
32.ADO.Net
33.Network
34.Directory Services
35.Security
36.unsafe
C# / C Sharp
C# / C Sharp by API
C# / CSharp Open Source
C# / CSharp Tutorial » Operator » Short Circuit Operators 
3.7.1.The short-circuit operators

The short-circuit AND operator is && and the short-circuit OR operator is ||.

As described earlier, their normal counterparts are & and |.

The normal operands will always evaluate each operand, but short-circuit versions will evaluate the second operand only when necessary.

using System; 
 
class Example {    
  public static void Main() {    
    int n, d; 
 
    n = 10
    d = 2
    if(d != && (n % d== 0
      Console.WriteLine(d + " is a factor of " + n)
 
    d = 0// now, set d to zero 
 
    Console.WriteLine("Since d is zero, the second operand is not evaluated.")
    if(d != && (n % d== 0
      Console.WriteLine(d + " is a factor of " + n);  
     
    Console.WriteLine("try the same thing without short-circuit operator. This will cause a divide-by-zero error.");
    if(d != (n % d== 0
       Console.WriteLine(d + " is a factor of " + n)
  }    
}
2 is a factor of 10
Since d is zero, the second operand is not evaluated.
try the same thing without short-circuit operator. This will cause a divide-by-zero error.

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
   at Example.Main()
3.7.Short Circuit Operators
3.7.1.The short-circuit operators
3.7.2.Side-effects of short-circuit operators
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.