Kapil
Kapil

Reputation: 9959

How to type cast in F#?

I have to enumerate through the members of a collection and create an array with a particular property of the members:

  let ops: int array = [| for x in app.Operations ->
                            let op=  x : IAzOperation
                            op.OperationID |] 

Here app.Operations is a collection of IAzOperation but on enumeration, returns each member as Obj. So I want to type cast each member and access the property. but not sure how to typecast it. If I typecast the way I've mentioned here, it gives me error that:

This espression was expected to have type IAzOPeration but here has type obj.

What am I missing here?

Upvotes: 23

Views: 13662

Answers (2)

pad
pad

Reputation: 41290

You need the downcasting operator :?>:

let ops: int array = [| for x in app.Operations do
                          let op =  x :?> IAzOperation
                          yield op.OperationID |] 

As the symbol ? in its name denotes, downcasting could fail and result in a runtime exception.

In case of sequences, you have another option to use Seq.cast:

let ops: int array = 
    [| for op in app.Operations |> Seq.cast<IAzOperation> -> op.OperationID |] 

Upvotes: 26

SmartestVEGA
SmartestVEGA

Reputation: 8889

type Base1() =
    abstract member F : unit -> unit
    default u.F() =
     printfn "F Base1"

type Derived1() =
    inherit Base1()
    override u.F() =
      printfn "F Derived1"


let d1 : Derived1 = Derived1()

// Upcast to Base1.
let base1 = d1 :> Base1

// This might throw an exception, unless
// you are sure that base1 is really a Derived1 object, as
// is the case here.
let derived1 = base1 :?> Derived1

// If you cannot be sure that b1 is a Derived1 object,
// use a type test, as follows:
let downcastBase1 (b1 : Base1) =
   match b1 with
   | :? Derived1 as derived1 -> derived1.F()
   | _ -> ()

downcastBase1 base1

Upvotes: 11

Related Questions