Option types in F# is equivalent to nullable types in C#, when an expression or a value can’t be evaluated or is invalid C# results in
, and here in F# it is
let divide x y = x / y
let divideSafe x = function
| y when y <> 0 -> Some(x/y)
| _ -> None
implementation if the divider is a non-zero value the value is evaluated. When it is zero, None is returned.
Accessing value from option type:
As in C# with nullable types, you should always check if an option type holds a value or not before accessing its value, otherwise an exception is thrown. Options module implements
for this check. If
, you can safely access the value as
. The following is another way of accessing the value with pattern matching.
let doMath x y =
let z = divideSafe x y
match z with
| None -> printfn "Oups! expression evaluated to nothing!"
| _ -> printfn "%s %d" "Expression evaluated to :" z.Value
Check blog post
] for comparison with C# version.