Casting within inheritance hierarchies
Casting between types is subtly different from converting between types.
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 screenshot:
- Change the statement to prefix the assigned variable named with a cast to the
Employee
type, as shown in the following code:Employee explicitAlice = (Employee)aliceInPerson;