C# Unchecked

Share:

About

In this code snippet, we’ll find out what the unchecked keyword does in C#.

The unchecked keyword is used to suppress arithmetic overflow exceptions. We will try to add two integers whose sum will exceed the size of the integer data type. This will cause an overflow to occur. The overflow would normally throw an exception, but if we wrap the expression with unchecked the exception will get suppressed and the integer will just overflow.

Note: You can also use the checked keyword to explicitly check for arithmetic overflow and throw an exception if it occurs.

Let’s check out the code example below. 

Code:

using System;

namespace Unckecked
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 2147483647;
            int b = 2147483647;

            //This will throw an overflow exception.
            //int c = a + b;

            //This will not throw an overflow exception and will just overflow.
            int c = unchecked(a + b);

            Console.WriteLine(c);

            Console.ReadLine();
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger