
C# 6 and .NET Core 1.0

Casting is subtly different from converting between different types.
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.
Going the other way, for example, attempting to store an instance of a base type in a variable of a derived type, 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 gives a compile error, as shown in the following screenshot:
Change the code as follows:
Employee e2 = (Employee)aliceInPerson;
The compiler is now happy but because aliceInPerson
might be a different derived type, such as a Student
instead of an Employee
, we need to be careful. This statement might throw an InvalidCastException
.
We can handle this by writing a try-catch
statement, but...
Change the font size
Change margin width
Change background colour