Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 18 CONVERSIONS

Explicit Conversions and Casting

When converting from a shorter type to a longer type, it’s 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 different values.

438

CHAPTER 18 CONVERSIONS

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 target type. If you want to make a conversion of this type, you must use an explicit conversion, called a cast expression.

The following code shows an example of a cast expression. It converts the value of var1 to type sbyte. A cast expression consists of the following:

A set of matching parentheses containing the name of the target type

The source expression, following the parentheses

Target type

(sbyte) var1;

Source expression

When you use a cast expression, you are explicitly taking responsibility for performing the operation that might lose data. Essentially, you are saying, “In spite of the possibility of data loss, I know what I’m doing, so make this conversion anyway.” (Make sure, however, that you do know what you’re doing.)

For example, Figure 18-6 shows cast expressions converting two values of type ushort to type byte. In the first case, there is no loss of data. In the second case, the most significant bits are lost, giving a value of 85—which is clearly not equivalent to the source value, 1,365.

Figure 18-6. Casting a ushort to a byte

The output of the code in the figure is the following:

sb: 10 = 0xA

sb: 85 = 0x55

439

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]