Information Technology Reference
In-Depth Information
Explicit Reference Conversions
Explicit reference conversions are reference conversions from a general type to a more special-
ized type.
￿
Explicit conversions include
-
Conversions from an object to any reference type
-
Conversions from a base class to a class derived from it
￿
The explicit reference conversions are illustrated by reversing each of the arrows in
Figures 18-18 and 18-19.
If this type of conversion were allowed without restriction, you could easily attempt to ref-
erence members of a class that are not actually in memory. The compiler, though, does allow
these types of conversions. When encountered at run time, however, the system raises an
exception.
For example, the code in Figure 18-20 converts the reference of base class A to its derived
class B , and assigns it to variable MyVar2 .
￿ f MyVar2 were to attempt to access Field2 , it would be attempting to access a field in the
B part” of the object, which is not in memory—causing a memory fault.
The runtime will catch this inappropriate cast and raise an InvalidCastException excep-
tion. Notice, however, that it does not cause a compile error.
￿
Figure 18-20. Invalid casts raise runtime exceptions.
Search WWH ::




Custom Search