What is the difference between the following F# casting operators? I can't seem to understand why and how they are all different.
(type) X
X :> type
X :?> type
What is the difference between the following F# casting operators? I can't seem to understand why and how they are all different.
(type) X
X :> type
X :?> type
The first isn't a cast in F#, though if you're used to C# it might appear that it works like one. But this is actually invoking a type conversion function (like
int
), and the parentheses aren't actually required (and are just likely to make everything more confusing).Note that this works for primitive types, because there are predefined conversion functions, but it won't work for arbitrary types:
The difference between the other two is that
:>
performs upcasts (from a type to a supertype, which is always safe) and:?>
performs downcasts (from a type to a subtype, which might fail, thus the'?'
in the middle).There are also named
upcast
anddowncast
operators which can be used in a similar way:In some contexts the target type of the upcast or downcast may be successfully inferred, in which case you don't need the type annotations when using the
upcast
ordowncast
operators, while you always need to provide a type argument to the:>
or:?>
operators (though you can supply_
if you expect it to be inferred):