Information Technology Reference
In-Depth Information
The third case is where the actual data pointed to by the source reference could safely
be converted implicitly. The following code shows an example, and Figure 18-21 illustrates
the code.
The implicit conversion in the second line makes MyVar2 “think” that it is pointing to
data of type A , while it is actually pointing to a data object of type B .
￿
￿
The explicit conversion in the third line is casting a reference of a base class to a refer-
ence of one of its derived classes. Normally this would raise an exception. In this case,
however, the object being pointed to is actually a data item of type B .
B MyVar1 = new B();
A MyVar2 = MyVar1; // Implicitly cast MyVar1 to type A.
B MyVar3 = (B)MyVar2; // This cast is fine because the data is of type B.
Figure 18-21. Casting to a safe type
Search WWH ::




Custom Search