An
object reference can be:
- Implicitly upcast to a base class reference
- Explicitly downcast to a subclass reference
Upcasting
and downcasting between compatible reference types performs reference
conversions: a new reference is (logically) created that points
to the same object.
An upcast always succeeds; a downcast succeeds
only if the object is suitably typed.
Upcasting
An
upcast operation creates a base class reference from a
subclass reference. For example:
Vechicle
oVechicle = new Vechicle();
Car
oCar = oVechicle; // Upcast
After
the upcast, variable oCar
still references the same Vechicle
object as variable oVechicle.
The object being referenced is not itself altered or converted:
Console.WriteLine
(oCar
== oVechicle); // True
Although
oCar
and oVechicle
refer to the identical object, oCar
has a more restrictive view on that object:
Console.WriteLine
(oCar.Name); // OK
Console.WriteLine
(oCar.VechicleCount); //
Error: VechicleCount undefined
The
last line generates a compile-time error because the variable oCar
is of type Car,
even though it refers to an object of type Vechicle.
To get to its VechicleCount
field, you must downcast the Vechicle
to a Car.
Downcasting
A
downcast operation creates a subclass reference from a base class
reference. For example:
Vechicle
oVechicle = new Vechicle();
Car
oCar = oVechicle; // Upcast
Vechicle
oVechicle1 = (Vechicle)oCar; // Downcast
Console.WriteLine
(oVechicle1.VechicleCount); // <No error>
Console.WriteLine
(oVechicle1 == oCar); // True
Console.WriteLine
(oVechicle1 == oVechicle); // True
As
with an upcast, only references are affected—not the underlying
object. A downcast requires an explicit cast because it can
potentially fail at runtime:
Maruti
oMaruti = new Maruti();
Car
oCar = oMaruti; // Upcast always succeeds
Vechicle
oVechicle = (Vechicle)oCar; // Downcast fails: oCar is not a Car
If
a downcast fails, an InvalidCastException is thrown.
This is an example of runtime type checking.
No comments:
Post a Comment