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:

Explicit casting

Change the code as follows:

    Employee e2 = (Employee)aliceInPerson; 

Handling casting exceptions

The compiler is now happy; but, because aliceInPerson might be a different derived type, like a Student instead of an 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, the as keyword returns null if the type cannot be cast.

Add the following statements to the end of the Main method:

    Employee e3 = aliceInPerson as Employee; 
    if (e3 != null) 
    { 
      WriteLine($"{nameof(aliceInPerson)} AS an Employee"); 
      // do something with e3 
    } 

Since accessing a null variable can throw a NullReferenceException error, you should always check for null before using the result.

Run the console application and view the output:

aliceInPerson AS an Employee

Tip

Good Practice

Use the is and as keywords to avoid throwing exceptions when casting between derived types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.0.85