C Sharp Checked and Unchecked

C# Checked and Unchecked

To handle integral type exceptions in C#, the checked and unchecked keywords are used. They thus define the checked context where arithmetic overflow raises an exception and the unchecked context where the arithmetic overflow is ignored and the result is truncated.

C# Checked:

To check the overflow explicitly, the checked keyword is used in C#. It also checks the conversion of the integral type values at compile time.

Example: Without using the checked keyword:

using System;  
namespace Example  
{  
    class num  
    {  
        static void Main(string[] args)   
        {  
                int n = int.MaxValue;  
                Console.WriteLine(n + 10);  
        }  
    }  
}

Output:

Explanation:

In the above example, the program does not throw any overflow exception, even after producing the wrong result. A truncated or wrong result (which may vary from system to system) is thus displayed on the console screen.

Example: Using the checked keyword:

using System;  
namespace Example  
{  
    class num  
    {  
        static void Main(string[] args)   
        { 
             checked  
            { 
                int n = int.MaxValue;  
                Console.WriteLine(n + 10); 
            }
        }  
    }  
}

Output:

Explanation:

In the above example, the program does throw an exception. Thus the program execution is stopped. Since the checked keyword in C# checks the overflow explicitly thus it produced the OverflowException when the performed arithmetic operation caused an overflow.

C# Unchecked:

The integral-type arithmetic exceptions are ignored by the C# Unchecked keyword. It may thus produce a truncated or wrong result, as it does not check explicitly.

Example:

using System;  
namespace Example  
{  
    class num  
    {  
        static void Main(string[] args)   
        { 
            unchecked  
            { 
                int n = int.MaxValue;  
                Console.WriteLine(n + 10); 
            }
        }  
    }  
}

Output:

Explanation:

In the above example, we displayed the use and behavior of the unchecked keyword in C#. Since the unchecked keyword in C# does not checks the data explicitly, a truncated or wrong result (which may vary from system to system) is thus displayed on the console screen.

Please Share