If you put the following code in a .NET 4.5 application:
public const long MAXIMUM_RANGE_MAGNITUDE = int.MaxValue + 1;
A compiler error is generated stating "The operation overflows at compile time in checked mode". I know that I could put this in an "unchecked" block and be fine, but my question is why does the error appear in the first place? Clearly a long can hold a int's max value plus one.
Note that using Int32 and Int64 instead of long and int does not seem to help.
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.
Your code in fact looks like this:
(long)(int.MaxValue + 1)
But because .Net framework has an inbuilt implicit conversion between int and long you do not have to explicitly put a cast to long in your code.
So firstly this part of the code is executed:
int.MaxValue + 1
and the result of this operation is an int
value which causes and overflow exception.
So your code does not even have a chance to start the conversion from int to long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With