In C#, in order to access a property/method I might downcast to a type and then access the property:
Fruit f = new Banana();
((Banana)f).Peel();
What is the equivalent in F#? I tried the following but the intellisense after typing the period does not give any members of the Banana
type so I'm guessing this isn't valid.
let f = new Banana()
(f :?> Banana).Peel()
I know I can do it by introducing an intermediate let
statement but was wondering if there was a one liner.
UPDATE
Ok I was trying to give a general example but I guess something got lost in my translation. I'm working with Excel interop. In any case here is the more specific code.
(worksheet.Cells.[rowNumber, dateColumn] :?> Excel.Range).<member here>
But it looks like it was just a temporary glitch in intellisense because today (after rebooting my computer) it seems to work fine. Yesterday it was just showing me basic object members of Equals, GetHashCode, GetType, and ToString
. Now today this same expression is giving me all the members of the Excel.Range
class. So I it looks like everything works as expected.
Your initial guess is correct, this code works:
type Fruit() =
member me.Test() = printfn "Test"
type Banana() =
inherit Fruit()
member me.Peel() = printfn "Peeling !"
let f = new Banana() :> Fruit
(f :?> Banana).Peel()
You are not showing how did you define those types, probably you have something wrong there.
Also keep in mind that in F# you have to be explicit to upcast. In your example your f
object is already a Banana
, nothing in your code upcast it to a Fruit
.