C# checked and unchecked keywords

Updated on     Kisan Patel

Checked and Unchecked statements are used to check the memory overflow exceptions.

The checked keyword is used to check the overflow for integral type arithmetic operations and conversations.

Overflow occurs when the value of a variable exceeds the required original length of the integral type arithmetic operations and conversations. Arithmetic overflow exceptions are raised in a checked context; whereas, in case of unchecked context, arithmetic overflow is ignored and the program displays the truncated integers from the result.

The following code snippet shows an example of checked and unchecked statements:

class Program
{
        public static void Main(string[] args)
        {
            byte number1, number2;
            byte result;
            number1 = 130;
            number2 = 130;
            try
            {
                result = unchecked((byte)(number1 * number2));
                Console.WriteLine("Unchecked result: " + result);
                result = checked((byte)(number1 * number2));
                Console.WriteLine("Checked result: " + result);
            }
            catch(OverflowException e){
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();
        }
}

In the above code, you can see that the OverflowException class is used to catch the overflow exception.

the output of the above C# program…

checked-uncheckde-c#


C#

Leave a Reply