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