Consider the following code:
long longMaxValue = long.MaxValue;
decimal decimalMaxValue = decimal.MaxValue;
int a = (int)longMaxValue;
int b = (int)decimalMaxValue;
Question #1: Why casting longMaxValue
to int
results in -1?
Question #2: Why casting decimalMaxValue
to int
results in the following exception BUT casting longMaxValue
to int
doesn't?
Value was either too large or too small for an Int32.
because long.MaxValue
is binary 0111111....1111; casting here basically cuts it down to the last (least significant) 32 bits - all of which are 1; and binary 111...111 is: -1
integer arithmetic is unchecked
in C# by default. Add checked
, or change the compiler to check by default, and it will error
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