Casting within inheritance hierarchies
Casting between types is subtly different from converting between types. Casting is between similar types, like between a 16-bit integer and a 32-bit integer, or between a superclass and one of its subclasses. Converting is between dissimilar types, like between text and a number.
Implicit casting
In the previous example, you saw how an instance of a derived type can be stored in a variable of its base type (or its base's base type, and so on). When we do this, it is called implicit casting.
Explicit casting
Going the other way is an explicit cast, and you must use parentheses around the type you want to cast into as a prefix to do it:
- In the
Main
method, add a statement to assign thealiceInPerson
variable to a newEmployee
variable, as shown in the following code:Employee explicitAlice = aliceInPerson;
- Visual Studio Code displays a red squiggle and a compile error, as shown in the following...