Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Why can't I use the :? operator in F# interactive?

I am trying to check if a variable is of a certain type like so:

let s = "abc"
let isString = s :? string

but in F# interactive, I get the following error:

error FS0016: The type 'string' does not have any proper subtypes and cannot be used as the source of a type test or runtime coercion.

Why is this happening? I expect isString to be a bool.

like image 522
user3685285 Avatar asked Oct 26 '25 12:10

user3685285


1 Answers

Because you are trying with a sealed type.

Try instead this:

let s = box "abc"
let isString = s :? string

There is no point in doing this coercion tests with sealed types since they can't have any subtype and that's what the error message is telling you.

The box keyword will always return an object, whether the source is reference type (as in this case) or a value type, in which case it will "box" it.

like image 169
Gus Avatar answered Oct 29 '25 06:10

Gus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!