Prototypical code in C#:
if(obj1 is ISomeInterface) {
do_something
}
Code in F# that doesn't compile:
match obj1 with
| :? ISomeInterface -> do_something
| _ -> ()
To add some explanation for the answers by desco and Brian - adding box
is needed when the static type of the obj1
value may not necessariliy be a .NET reference type.
If the type of obj1
is obj
(type alias for System.Object
) then you can use pattern matching without any boxing, because the compiler already knows you have a reference type:
let obj1 : obj = upcast (...)
match obj1 with
| :? ISomeInterface -> (do something)
The case where you need box
is when the type of obj1
is generic type parameter. In this case, your function can be called with both value types and reference types. Adding box
ensures that you're performing type test on reference type (and not on value type, which is not possible).
match box obj1 with
| :? ISomeInterface -> do_something
| _ -> ()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With