Information Technology Reference
In-Depth Information
Explicit Conversions and Casting
When converting from a shorter type to a longer type, it is easy for the longer type to hold all
the bits of the shorter type. In other situations, however, the target type might not be able to
accommodate the source value without loss of data.
For example, suppose you want to convert a ushort value to a byte .
￿A ushort can hold any value between 0 and 65,535.
￿A byte can only hold a value between 0 and 255.
As long as the ushort value you want to convert is less than 256, there won't be any loss
of data. If it is greater, however, the most significant bits will be lost.
￿
For example, Figure 18-5 shows an attempt to convert a ushort with a value of 1,365 to a
byte , resulting in a loss of data.
Figure 18-5. Attempting to convert a ushort to a byte
Clearly, only a relatively small number (0.4 percent) of the possible unsigned 16-bit ushort
values can be safely converted to an unsigned 8-bit byte type without loss of data. The rest
result in data overflow , yielding a different value.
Casting
For the predefined types, C# will automatically convert from one data type to another—but
only between those types for which there is no possibility of data loss between the source type
and the target type. That is, the language does not provide automatic conversion between two
types if there is any value of the source type that would lose data if it were converted to the tar-
get type. If you want to make a conversion of this type, it must be an explicit conversion , using
a cast expression .
Search WWH ::




Custom Search