Information Technology Reference
In-Depth Information
What Are Conversions?
Consider the simple case in which you declare two variables of different types, and then assign
the value of one (
the source
) to the other (
the target
). Before the assignment can occur, the
source value must be converted to a value of the target type. Figure 18-1 illustrates type
conversion.
•
Conversion
is the process of taking a value of one type and
using it as
the equivalent
value of another type.
The value resulting from the conversion should be the same as the source value—but in
the target type.
Figure 18-1.
Type conversion
For example, the code in Figure 18-2 shows the declaration of two variables of different types.
Var1
is of type
short
, a 16-bit signed integer that is initialized to
5
.
Var2
is of type
sbyte
,
an 8-bit signed integer that is initialized to the value
10
.
The third line of the code assigns the value of
Var1
to
Var2
. Since these are two different
types, the value of
Var1
must be converted to a value of the same type as
Var2
before the
assignment can be performed. This is performed using the
cast expression
, which you
will see shortly.
Notice also that the value and type of
Var1
are unchanged. Although it is called a
conver-
sion
, this only means that the source value is
used as
the target type.
Figure 18-2.
Converting from a short to an sbyte