Home

Class Inheritance: Down-Casting an Object

   

Introduction

Down-casting is the ability to convert an object to a class that is a child of the one that served to create the object. The operator used to perform this operation is :?>. The formula to follow is:

Some-Object :?> Child-Class

As you can imagine, down-casting is the opposite to up-casting. Up-casting is easy because it relies on implicit (or obvious) inheritance. When you decide to down-cast, the compiler must find out whether the class used to create your object has a child. For this reason, the compiler waits until the application executes to resolve the compatibility issue.

To down-cast, you can first create an object, up-cast it to the appropriate parent class, then down-cast as necessary. This can be done as follows:

type Person(first, last) =
    member this.FirstName : string = first
    member this.LastName  : string = last

type Customer(first, last, acntNumber)=
    inherit Person(first, last)
        member this.AccountNumber : string = acntNumber
        member this.FullName = base.LastName + ", " + base.FirstName
        new(first, last) = Customer(first, last, "0000-000-0000")

type Employee(emplNumber, first, last, acntNumber, employmentStatus, salary) =
    inherit Customer(first, last, acntNumber)
        member this.EmployeeNumber : string = emplNumber
        member this.EmploymentStatus : string = "Full-Time"
        member this.Salary : int = salary
        new(first, last) = Employee("0000-0000", first, last, "0000-000-0000", "Unknown", 0)
        new(emplNumber, first, last) = Employee(emplNumber, first, last, "0000-000-0000", "Unknown", 0)
        new(emplNumber, first, last, acntNumber) = Employee(emplNumber, first, last, acntNumber, "Unknown", 0)

let empl = new Employee("8204-5083", "Meghan", "Walley", "2735-038-4058")
// Getting a Customer side from an Employee object
let client = empl :> Customer;
// Getting the customer information from an Employee child object
let customer  = client :?> Employee
     
     
 

Home Copyright © 2009-2015, FunctionX Home