SoFunction
Updated on 2025-04-11

Use of c# checked and unchecked keywords

In C#,checked Keywords are used to enable overflow checking of integer operations. By default, integer operations in C# do not automatically perform overflow checks, which means that if an overflow occurs (i.e., the result is beyond the representation of the data type), the program will continue to run, but the result may be incorrect. Use the checked keyword to catch these overflows at compile time or runtime and throwException.

using System;

class Program
{
    static void Main()
    {
        try
        {
            int maxInt = ;
            int value = 10;

            // Use checked for overflow checking            int result = checked(maxInt + value);
            ("Result: " + result);
        }
        catch (OverflowException ex)
        {
            ("Overflow exception: " + );
        }
}
  • checked: Enable overflow checking, if overflow occurs, throw
  • unchecked: Disable overflow checking, no exception is thrown even if an overflow occurs (default behavior)
int maxInt = ;
int value = 10;

// Enable overflow checkingchecked
{
    int result = maxInt + value;  // Throw out}

// Disable overflow checkingunchecked
{
    int result = maxInt + value;  // The result is incorrect, but the exception will not be thrown}

This is the end of this article about the use of c# checked and unchecked keywords. For more related contents of c# checked and unchecked keywords, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!