As far as I know, F# doesn't have any built-in operator equivalent to C# as
so you need to write some more complicated expression. Alternatively to your code using match
, you could also use if
, because the operator :?
can be use in the same way as is
in C#:
let res = if (inputValue :? Type1) then inputValue :?> Type1 else null
You can of course write a function to encapsulate this behavior (by writing a simple generic function that takes an Object
and casts it to the specified generic type parameter):
let castAs<'T when 'T : null> (o:obj) =
match o with
| :? 'T as res -> res
| _ -> null
This implementation returns null
, so it requires that the type parameter has null
as a proper value (alternatively, you could use Unchecked.defaultof<'T>
, which is equivalent to default(T)
in C#). Now you can write just:
let res = castAs<Type1>(inputValue)