Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Casting of BankAccounts

Here is the program we deal with. The comments explain each of the six cases.

using System; 

class App {

  public static void Main(){
    BankAccount ba1 = new BankAccount("George", 1000.0M, 0.01),
                ba2 = new CheckAccount("Bill", 2000.0M, 0.01);

    CheckAccount caRes1, caRes2, caRes3, caRes4, caRes5, caRes6; 

    CheckAccount ca = new CheckAccount("John", 2000.0M, 0.01);

//    caRes1 = (BankAccount)ba1;     // Cannot implicitly convert type 'BankAccount' to 'CheckAccount'
      caRes2 = (CheckAccount)ba1;    // Illegal downcasting. Run-time error. Compiles

//    caRes3 = (BankAccount)ba2;     // Cannot implicitly convert type 'BankAccount' to 'CheckAccount'.
      caRes4 = (CheckAccount)ba2;    // OK because ba2 refers to a CheckAccount

//    caRes5 = (BankAccount)ca;      // Cannot implicitly convert type 'BankAccount' to 'CheckAccount'.
      caRes6 = (CheckAccount)ca;     // OK because ca is a CheckAccount