Q&A
Ask and answer questions to make information more available to wider audiences.
Roman Tuttle @tuttleroman   22, May 2023 12:00 AM
upcasting and downcasting
What is upcasting and downcasting in F#?
answers 2
 
Answer 1
Payton Leonard @leonardpayton   31, May 2023 12:17 PM
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()  

 
Answer 2
London Leon @leonlondon852   31, May 2023 12:03 PM
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.