Home  >  Article  >  Backend Development  >  C# checked and unchecked usage

C# checked and unchecked usage

黄舟
黄舟Original
2016-12-28 10:47:531725browse

checked keyword is used to explicitly enable overflow checking for integer arithmetic operations and conversions.

By default, if an expression contains only constant values, it causes a compiler error if the resulting value is outside the range of the target type. If the expression contains one or more non-constant values, the compiler does not detect overflow. In the following example, evaluating the expression assigned to i2 does not cause a compiler error.

// The following example causes compiler error CS0220 because 2147483647 
// is the maximum value for integers.  
//int i1 = 2147483647 + 10; 
  
// The following example, which includes variable ten, does not cause 
// a compiler error. 
int ten = 10; 
int i2 = 2147483647 + ten; 
  
// By default, the overflow in the previous statement also does 
// not cause a run-time exception. The following line displays  
// -2,147,483,639 as the sum of 2,147,483,647 and 10. 
Console.WriteLine(i2);

By default, these non-constant expressions are not checked for overflow at runtime, and these expressions do not throw an overflow exception. The above example shows -2,147,483,639 as the sum of two positive integers.

Overflow checking can be enabled through compiler options, environment configuration, or using the checked keyword. The following example demonstrates how to use a checked expression or a checked block to detect at runtime an overflow caused by a previous sum calculation. Both examples throw overflow exceptions.

// If the previous sum is attempted in a checked environment, an 
// OverflowException error is raised.

// Checked expression.
Console.WriteLine(checked(2147483647 + ten));

// Checked block.
checked
{
    int i3 = 2147483647 + ten;
    Console.WriteLine(i3);
}

Overflow checking can be canceled using unchecked

This example demonstrates how to use checked to enable runtime overflow checking.

class OverFlowTest
{
    // Set maxIntValue to the maximum value for integers.
    static int maxIntValue = 2147483647;

    // Using a checked expression.
    static int CheckedMethod()
    {
        int z = 0;
        try
        {
            // The following line raises an exception because it is checked.
            z = checked(maxIntValue + 10);
        }
        catch (System.OverflowException e)
        {
            // The following line displays information about the error.
            Console.WriteLine("CHECKED and CAUGHT:  " + e.ToString());
        }
        // The value of z is still 0.
        return z;
    }

    // Using an unchecked expression.
    static int UncheckedMethod()
    {
        int z = 0;
        try
        {
            // The following calculation is unchecked and will not 
            // raise an exception.
            z = maxIntValue + 10;
        }
        catch (System.OverflowException e)
        {
            // The following line will not be executed.
            Console.WriteLine("UNCHECKED and CAUGHT:  " + e.ToString());
        }
        // Because of the undetected overflow, the sum of 2147483647 + 10 is 
        // returned as -2147483639.
        return z;
    }

    static void Main()
    {
        Console.WriteLine("\nCHECKED output value is: {0}",
                          CheckedMethod());
        Console.WriteLine("UNCHECKED output value is: {0}",
                          UncheckedMethod());
    }
    /*
   Output:
   CHECKED and CAUGHT:  System.OverflowException: Arithmetic operation resulted
   in an overflow.
      at ConsoleApplication1.OverFlowTest.CheckedMethod() 

   CHECKED output value is: 0
   UNCHECKED output value is: -2147483639
 */
}

The above is the content of C# checked and unchecked usage. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn