How Explicit Casts Fail

When doing explicit numeric conversions, it’s possible that the value of the source type cannot be exactly represented in the destination type.  When this happens, one of several things may occur:
  • Integer to integer: extra bits discarded
  • Decimal to integer: truncates
  • Float/Double to integer: truncates
  • Double to float: rounded, or set to “infinity” value if too large
  • Float/Double to decimal: rounded
  • Decimal to float/double: loss of precision
The checked keyword can be used to throw exception if result is out of range.
Examples:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
long l = (long)int.MaxValue + 1;      // l = 2147483648
int i = (int)l;                       // i set to -2147483648 (same hex value)
i = checked((int)l);  // Throws OverflowException
 
l = 0x2200000005;     // Try larger number
i = (int)l;           // i set to 5
i = checked((int)l);  // Throws OverflowException
 
float f = 4.8f;
i = (int)f;           // i set to 4 (truncated)
i = checked((int)f);  // i set to 4 (truncated)
 
double d = 1.000008;
f = (float)d;         // f set to 1.000008  (no loss of data)
d = 1.00000008;
f = (float)d;         // f rounded to 1.00000012