CA2233: Operations should not overflow
TypeName | OperationsShouldNotOverflow |
CheckId | CA2233 |
Category | Microsoft.Usage |
Breaking Change | Non Breaking |
Arithmetic operations should not be performed without first validating the operands to make sure that the result of the operation is not outside the range of possible values for the data types involved. Depending on the execution context and the data types involved, arithmetic overflow can result in either a System.OverflowException or the most significant bits of the result discarded.
Description
A method in the following example manipulates an integer that violates this rule. Visual Basic requires the Remove integer overflow option to be disabled for this to fire.
Code
Comments
If the method in this example is passed MinValue, the operation would underflow. This causes the most significant bit of the result to be discarded. The following code shows how this occurs.
[C#]
public static void Main()
{
int value = int.MinValue; // int.MinValue is -2147483648
value = Calculator.Decrement(value);
Console.WriteLine(value);
}
[VB]
Public Shared Sub Main() Dim value = Integer.MinValue ' Integer.MinValue is -2147483648 value = Calculator.Decrement(value) Console.WriteLine(value) End Sub
Output
2147483647
Description
The following example fixes the previous violation by wrapping the operation in a checked block. If the operation causes an overflow, a System.OverflowException will be thrown.
Note that checked blocks are not supported in Visual Basic.
Code
using System; namespace Samples { public static class Calculator { public static int Decrement(int input) { checked { input--; } return input; } } }
If you turn on checked arithmetic overflow/underflow in C#, it is equivalent to wrapping every integer operation in a checked block.
To turn on checked arithmetic overflow/underflow in C#
In Solution Explorer, right-click your project and choose Properties.
Select the Build tab and click Advanced.
Select Check for arithmetic overflow/underflow and click OK.