Information Technology Reference
In-Depth Information
The following code shows an example of a cast expression. It converts the value of Var1 to
type sbyte . A cast expression consists of
￿
A set of matching parentheses containing the name of the target type
￿
The source expression, following the parentheses
Target type
( sbyte ) Var1;
Source expression
In using a cast expression, you are explicitly taking responsibility for performing the oper-
ation 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
Search WWH ::




Custom Search