December 2018
Beginner to intermediate
668 pages
15h 30m
English
The compiler is now happy; but, because aliceInPerson might be a different derived type, like Student instead of Employee, we need to be careful. This statement might throw an InvalidCastException error.
We can handle this by writing a try statement, but there is a better way. We can check the current type of the object using the is keyword.
Wrap the explicit cast statement in an if statement, as follows:
if (aliceInPerson is Employee)
{
WriteLine($"{nameof(aliceInPerson)} IS an Employee");
Employee e2 = (Employee)aliceInPerson;
// do something with e2
}
Run the console application and view the output:
aliceInPerson IS an Employee
Alternatively, you can use the as keyword to cast. Instead of throwing an exception, ...
Read now
Unlock full access