Why does int32.maxvalue + 1 overflow a long?

It is because the calculations on the right hand side of assignment is being done in integer type. And it is overflowing integer

You can fix that with:

public const long MAXIMUM_RANGE_MAGNITUDE = int.MaxValue + (long)1; // or 1L

By casting at least one of the operand to long

The reason you get the error is specified in C# specifications.

See C# Specification Section 4.1.5 (Integral types)

For the binary +, –, *, /, %, &, ^, |, ==, !=, >, <, >=, and <=
operators, the operands are converted to type T, where T is the first
of int, uint, long, and ulong that can fully represent all possible
values of both operands.
The operation is then performed using the
precision of type T, and the type of the result is T (or bool for the
relational operators). It is not permitted for one operand to be of
type long and the other to be of type ulong with the binary operators.

In your case since both operands of addition can be represented in int therefore the calculation is done in integer type. Explicitly casting one of the operand to long would result in long result and thus no overflow error.

Leave a Comment