Google News
logo
F# - Interview Questions
What is upcasting and downcasting in F#?
Casting is a process of converting one type to another type. F# provides mainly two operators to deal with upcasting and downcasting. The :> operator is used to upcast object and :?> operator is used to downcast object.
 
Example :
type BaseClass() =  
 class  
  member this.ShowClassName()=  
    printfn "BaseClass"  
 end  
  
type DerivedClass() =   
 class  
  inherit BaseClass()  
  member this.ShowClassName()=  
   printfn "DerivedClass"  
 end  
  
let baseClass = new BaseClass()              
let derivedClass : DerivedClass = new DerivedClass()  
baseClass.ShowClassName()      
derivedClass.ShowClassName()  
let castIntoBaseClass = derivedClass :> BaseClass        // upcasting   
castIntoBaseClass.ShowClassName()  
let castIntoDerivedClass = baseClass :?> DerivedClass   // downcasting  
castIntoDerivedClass.ShowClassName()
Advertisement