Home > Articles

  • Print
  • + Share This
This chapter is from the book

Converting Data Types

When you move a value from one variable type to another, a conversion must occur. Additionally, if you want to perform an operation on two different data types, a conversion might also need to occur. Two types of conversions can occur: implicit and explicit.

Implicit conversions happen automatically without error. You've read about many of these within today's lesson. What happens when an implicit conversion is not available? For example, what if you want to put the value stored in a variable of type long into a variable of type int?

Explicit conversions are conversions of data that are forced. For the value data types that you learned about today, the easiest way to do an explicit conversion is with a cast. A cast is the forcing of a data value to another data type. The format of a cast is shown here:

ToVariable = (datatype) FromVariable;

datatype is the data type that you want the FromVariable converted to. Using the example of converting a long variable to an int, you enter the following statement:

int IntVariable = 0;
long LongVariable = 1234;
IntVariable = (int) LongVariable;

In doing casts, you take responsibility for making sure that the variable can hold the value being converted. If the receiving variable cannot store the received value, truncation or other changes can occur. A number of times, you will need to do explicit conversions. Table 3.4 contains a list of those times.

NOTE

Explicit conversions as a group also encompass all the implicit conversions. It is possible to use a cast even if an implicit conversion is available.

Table 3.4 Required Explicit Conversions

From Type

To Type(s)

sbyte

byte, ushort, uint, ulong, or char

byte

sbyte or char

short

sbyte, byte, ushort, uint, ulong, or char

ushort

sbyte, byte, short, or char

int

sbyte, byte, short, ushort, uint, ulong, or char

uint

sbyte, byte, short, ushort, int, or char

long

sbyte, byte, short, ushort, int, uint, ulong, or char

ulong

sbyte, byte, short, ushort, int, uint, long, or char

char

sbyte, byte, or short

float

sbyte, byte, short, ushort, int, uint, long, ulong, char, or decimal

double

sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or decimal

decimal

sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or double


  • + Share This
  • 🔖 Save To Your Account