find and solve || findandsolve.com
Please wait.....

C# Checked and Unchecked

In the c# statements can execute in either checked or unchecked context. In a checked context, arithmetic overflow raises an exception and then an unchecked context, arithmetic overflow is ignored and the result is truncated.

C# Checked

The checked keyword is used to explicitly check overflow and conversion of integral type values at compile time.

C# Checked Example without using checked

using System;  
namespace FindAndSolve
{
    public class Program
    {
        public static void Main(string[] args)
        {
                int a = int.MaxValue;
                Console.WriteLine(a + 3);
        }
    }
}  

Output

-2147483646

In the given above program produces the wrong result and does not throw any overflow exception.

C# Checked Example using checked

using System;  
namespace FindAndSolve {
    public class Program
    {
        public static void Main(string[] args)
        {
            checked
            {
                int a = int.MaxValue;
                Console.WriteLine(a + 3);
            }
        }
    }
}  

Output

Run-time exception (line 11): Arithmetic operation resulted in an overflow.

Stack Trace:

[System.OverflowException: Arithmetic operation resulted in an overflow.]

   at FindAndSolve.Program.Main(String[] args) :line 11


C# Unchecked

In the C# Unchecked keyword ignores the integral type arithmetic exceptions. It does not check explicitly and produce result that may be truncated or wrong.

using System;  
namespace FindAndSolve  
{
    public class Program
    {         public static void Main(string[] args)
        {             unchecked             {
                int a = int.MaxValue;
                Console.WriteLine(a + 2);
            }
        }
    }
}

Output

-2147483647