Question

How can I use DbCommand.ExecuteScalar from F#? It returns an obj which I need to convert to an int. I'm very new to F# and the casting I need to do is not clear.

let (stockid:uint32) = command.ExecuteScalar()

Compile Error: 
Type constraint mismatch. The type   obj is not compatible with type  uint32 

Upcasting using :?> throws a runtime error.

Was it helpful?

Solution

If you just say

let o : obj = ...
printfn "%s" (o.GetType().ToString())

what do you get? Is it indeed an int? (int32 or uint32 or what?)

The :?> operator is the correct downcast operator, but you need the types to match. After casting to the actual type, if you need to convert from one integral type to another, then use the corresponding function for the destination type, e.g.

let x : int = int myUnsignedInt  
// first 'int' is type, second is function to convert-to-int

OTHER TIPS

If the Downcast (:?>) throws at runtime, you're not getting a unit32 as a return value from the Execute Scalar. You should be able to convert ...

let stockid : uint32 = unit32 command.ExecuteStalar()

But if you're getting something that can't be converted to an uint32, that will fail too.More on casting and converting here.

Try casting it to an int32 instead of a uint32. ExecuteScalar returns an object of int32.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top