Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check in F# whether object implements interface

Prototypical code in C#:

if(obj1 is ISomeInterface) {
   do_something
}

Code in F# that doesn't compile:

match obj1 with 
| :? ISomeInterface -> do_something
| _ -> ()
like image 424
Alfa07 Avatar asked Mar 20 '11 13:03

Alfa07


2 Answers

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).

like image 110
Tomas Petricek Avatar answered Oct 08 '22 04:10

Tomas Petricek


match box obj1 with 
| :? ISomeInterface -> do_something
| _ -> ()
like image 14
desco Avatar answered Oct 08 '22 03:10

desco