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

  • Long 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
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #48 – How Explicit Casts Fail

  1. Pingback: #1,048 – No Implicit Conversions between Signed vs. Unsigned | 2,000 Things You Should Know About C#

  2. Your first bullet, “Integer to integer”, I believe you meant to be “Long to integer”.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: