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(); } } }