Saturday, March 26, 2011

Studying F# : Upcasting and Downcasting

In normal object-oriented languages, upcasting is implicit and downcasting is explicit. But, in F#, Both upcasting and downcasting are explicit. Suppose we have 2 classes like below:
[<Class>]
type Person(fn, ln, a) =
    member p.FirstName = fn
    member p.LastName = ln
    member p.Age = a
[<Class>]
type Student(fn, ln, a, sub, sch) =
    inherit Person(fn, ln, a)
    member p.Subject = sub
    member p.School = sch


Upcasting

The way to use upcast keyword:
let p_base_1 : Person = upcast new Student("aaa", "aa", 11, "111", "1111")

The way to use upcasting operator:
let p_base_2 : Person = new Student("aaa", "aa", 11, "111", "1111") :> Person

Downcasting

The way to use downcast keyword:
let s_derived_1 : Student = downcast p_base_1

The way to use downcasting operator:
let s_derived_2 : Student = p_base_2 :?> Student

No comments:

Post a Comment