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






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 != 0 && (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 != 0 && (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 != 0 & (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