#48 – 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:

 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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers