Casting and Reference Conversions - CSharp Custom Type

CSharp examples for Custom Type:Polymorphism

Introduction

An object reference can be:

  • Implicitly upcast to a base class reference
  • Explicitly downcast to a subclass reference

Upcasting

An upcast operation creates a base class reference from a subclass reference.

For example:


public class Item
{
  public string Name;
}

public class Stock : Item   // inherits from Item
{
  public long SharesOwned;
}

public class Company : Item   // inherits from Item
{
  public decimal Mortgage;
}
     
     
Stock msft = new Stock();
Item a = msft;              // Upcast

After the upcast, variable a still references the same Stock object as variable msft.

Console.WriteLine (a == msft);        // True

Although a and msft refer to the identical object, a has a more restrictive view on that object:

Console.WriteLine (a.Name);           // OK
Console.WriteLine (a.SharesOwned);    // Error: SharesOwned undefined

Downcasting

A downcast operation creates a subclass reference from a base class reference.

For example:

Stock msft = new Stock();
Item a = msft;                      // Upcast
Stock s = (Stock)a;                  // Downcast
Console.WriteLine (s.SharesOwned);   // <No error>
Console.WriteLine (s == a);          // True
Console.WriteLine (s == msft);       // True

A downcast requires an explicit cast because it can potentially fail at runtime:

Company h = new Company();
Item a = h;               // Upcast always succeeds
Stock s = (Stock)a;        // Downcast fails: a is not a Stock

Related Tutorials