The short-circuit operators : Short Circuit Operators : Operator C# Examples


C# Examples » Operator » Short Circuit Operators »

 

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  !=  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);  
    }        
}
    
   
  
   



Output

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()


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Operator
» Short Circuit Operators