The exercise shows the behavior of various numeric types when they overflow, i.e. when their capacity is insufficient to contain the value resulting from a computation such as an arithmetic operation or cast.
byte
, ushort
, uint
, ulong
) will wrap around to zero (the type's maximum value + 1 acts as a modulus) unless broadly speaking they appear within a checked
block in which case an instance of OverflowException
is thrown. int
and long
will behave similarly except that they wrap around to int.MinValue
and long.minValue
respectively.int one = 1;
checked
{
int expr = int.MaxValue + one; // overflow exception is thrown
}
// or
int expr2 = checked(int.MaxValue + one); // overflow exception is thrown
checked
state applies only to expressions directly in the block. Overflow states in called functions are not caught.float
and double
types will adopt a state of infinity that can be tested wtih float.IsInfinity()
etc.double d = double.MaxValue;
d *= 2d;
Double.IsFinite(d)
// => false
decimal
will cause an instance of OverflowException
to be thrown.unchecked
keyword for circumstances where you want to reverse the effect of unchecked
inside a checked
block or when the compiler setting has been used.Overflows that occur without an exception being thrown can be problematic because it's generally true that the earlier an error condition can be reported the better.
Problems with overflows for int
and float
can be mitigated by assigning the result to a variable of type long
, decimal
or double
.
If large integers are essential to your code then using the BigInteger
type is an option.
Naturally there are occasions on which it is legitimate to allow an integer to wrap around particularly in the case of unsigned values. A classic case is that of hash codes that use the width of the integer as a kind of modulo.
You will usually find in code bases that there is often no check where an uint
or a ulong
is used as an identifier because it is considered more trouble than it's worth. This also applies where it is evident from the domain that no very large values will be involved. But, look at this for a cautionary tale.