Share via


Operations should not overflow

TypeName

OperationsShouldNotOverflow

CheckId

CA2233

Category

Microsoft.Usage

Breaking Change

NonBreaking

Cause

A method performs an arithmetic operation and does not validate the operands beforehand to prevent overflow.

Rule Description

Arithmetic operations should not be performed without first validating the operands to make sure 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.

How to Fix Violations

To fix a violation of this rule, validate the operands before you perform the operation.

When to Exclude Warnings

It is safe to exclude a warning from this rule if the possible values of the operands will never cause the arithmetic operation to overflow.

Example

The following example shows a method that contains an operation that manipulates an integer that violates this rule. Visual Basic requires the Remove integer overflow option to be disabled for this to fire.

In the above example, if Int32.MinValue was passed for input parameter. Then the operation would underflow causing the most significant bit of the result to be discarded.

The following example shows this.

.

The following example fixes the above violation by validating the value of input.

The following example fixes the above violation by wrapping the operation in a checked block.

When the above operation overflows, a System.OverflowException will be thrown.

Note: There is no checked block equivalent for Visual Basic

output.

Fixing this violation by turning on check arithmetic overflow/underfow.

To turn on check arithmetic overflow/underflow, follow these steps:

C#:

In Solution Explorer right-click your project, click Properties

Visual Basic:

In Solution Explorer right-click your project and choose Properties

See Also

Reference

C# Operators
Checked and Unchecked (C# Reference)
System.OverflowException