Casting within inheritance hierarchies
Casting 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 to do it.
In the Main
method, add the following code:
Employee e2 = aliceInPerson;
Visual Studio 2017 and Visual Studio Code display a red squiggle and a compile error in the Error List and Problems window, as shown in the following screenshot:
Change the code ...
Get C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.