HI WELCOME TO SIRIS

C# Checked and Unchecked

Leave a Comment
C# provides checked and unchecked keyword to handle integral type exceptions. Checked and unchecked keywords specify checked context and unchecked context respectively. In checked context, arithmetic overflow raises an exception whereas, in an unchecked context, arithmetic overflow is ignored and result is truncated.

C# Checked

The checked keyword is used to explicitly check overflow and conversion of integral type values at compile time.
Let's first see an example that does not use checked keyword.

C# Checked Example without using checked

  1. using System;  
  2. namespace CSharpProgram  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)   
  7.         {  
  8.                 int val = int.MaxValue;  
  9.                 Console.WriteLine(val + 2);  
  10.         }  
  11.     }  
  12. }  
Output:
-2147483647
See, the above program produces the wrong result and does not throw any overflow exception.

C# Checked Example using checked

This program throws an exception and stops program execution.
  1. using System;  
  2. namespace CSharpProgram  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)   
  7.         {  
  8.             checked  
  9.             {  
  10.                 int val = int.MaxValue;  
  11.                 Console.WriteLine(val + 2);  
  12.             }  
  13.         }  
  14.     }  
  15. }  
Output:
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.

C# Unchecked

The Unchecked keyword ignores the integral type arithmetic exceptions. It does not check explicitly and produce result that may be truncated or wrong.
Example
  1. using System;  
  2. namespace CSharpProgram  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)   
  7.         {  
  8.             unchecked  
  9.             {  
  10.                 int val = int.MaxValue;  
  11.                 Console.WriteLine(val + 2);  
  12.             }  
  13.         }  
  14.     }  
  15. }  
Output:
-2147483647

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.