In C# I can do:
var castValue = inputValue as Type1
In F#, I can do:
let staticValue = inputValue :> Type1
let dynamicValue = inputValue :?> Type1
But neither of them is the equivalent of the C#’s keyword as.
I guess I need to do a match expression for the equivalent in F#
match inputValue with
| :? Type1 as type1Value -> type1Value
| _ -> null
Is this correct?
As far as I know, F# doesn’t have any built-in operator equivalent to C#
asso you need to write some more complicated expression. Alternatively to your code usingmatch, you could also useif, because the operator:?can be use in the same way asisin C#:You can of course write a function to encapsulate this behavior (by writing a simple generic function that takes an
Objectand casts it to the specified generic type parameter):This implementation returns
null, so it requires that the type parameter hasnullas a proper value (alternatively, you could useUnchecked.defaultof<'T>, which is equivalent todefault(T)in C#). Now you can write just: