Lecture overview -- Keyboard shortcut: 'u'  Previous page: Overriding the Equals method in a class -- Keyboard shortcut: 'p'  Next page: Upcasting and downcasting in C# -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home  Page 38 : 40
Object-oriented Programming in C#
Specialization, Extension, and Inheritance
Upcasting and downcasting in C#

Upcasting converts an object of a specialized type to a more general type

Downcasting converts an object from a general type to a more specialized type

A specialization hierarchy of bank accounts

    BankAccount    ba1,
                   ba2 =   new BankAccount("John", 250.0M, 0.01);
    LotteryAccount la1,
                   la2 =   new LotteryAccount("Bent", 100.0M);

    ba1 = la2;                    // upcasting   - OK
//  la1 = ba2;                    // downcasting - Illegal 
                                  //   discovered at compile time
//  la1 = (LotteryAccount)ba2;    // downcasting - Illegal
                                  //   discovered at run time
    la1 = (LotteryAccount)ba1;    // downcasting - OK 
                                  //   ba1 already refers to a LotteryAccount

An illustration of upcasting and downcasting.