#47 – Numeric Conversions Through Casting

A conversion needs to happen when assigning a numeric value of one type to a variable of a different type.

Data values can be implicitly (automatically) converted whenever the conversion would not result in a loss of data.  This is possible if the target type has a wider range of types or greater precision than the source type.

Implicit conversion:

 int i = 12;
 long l = i;     // Implicit (int to long)
 float f = i;    // Implicit (int to float)
 double d = 4.2f;  // Implicit (float to double)

An explicit conversion is required when the conversion cannot be done without losing data.  These conversions require a cast operator that specifies the target type.

Explicit conversion:

 long l = 12;
 int i = l;        // Compiler error--can't implicitly convert
 int i = (int)l;     // Explicit (long to int)
 float f = 4.2f;
 i = (int)f;         // Explicit (float to int)
 double d = 4.2f;
 f = (float)d;       // Explicit (double to float)

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

2 Responses to #47 – Numeric Conversions Through Casting

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

  2. Pingback: #1,049 – Full List of Implicit Numeric Conversions | 2,000 Things You Should Know About C#

Leave a comment