Using checked and unchecked with statement blocks. : Data Type Cast : Data Type C# Examples


C# Examples » Data Type » Data Type Cast »

 

Using checked and unchecked with statement blocks.









    
using  System;  
  
class  MainClass  {    
    public  static  void  Main()  {    
        byte  a,  b;  
        byte  result;  
  
        a  =  127;  
        b  =  127;  
    
        try  {    
            unchecked  {  
                result  =  unchecked((byte)(a  *  b));  
                Console.WriteLine("Unchecked  result:  "  +  result);  
  
                result  =  unchecked((byte)(a  *  b));  
                Console.WriteLine("Unchecked  result:  "  +  result);  
            }  
  
            checked  {  
                result  =  checked((byte)(a  *  b));  
                Console.WriteLine("Checked  result:  "  +  result);  
  
                result  =  checked((byte)(a  *  b));  
                Console.WriteLine("Checked  result:  "  +  result);  
            }  
        }    
        catch  (OverflowException  exc)  {    
            //  catch  the  exception    
            Console.WriteLine(exc);  
        }    
    }    
}
    
   
  
   



Output

Unchecked result: 1
Unchecked result: 1
System.OverflowException: Arithmetic operation resulted in an overflow.
   at MainClass.Main()


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Data Type
» Data Type Cast