Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / F#

F# example usage of option types

0.00/5 (No votes)
4 Feb 2012CPOL 12.7K  
F# example usage of option types
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 null, and here in F# it is None.

C#
let divide x y = x / y

let divideSafe x = function
    | y when y <> 0 -> Some(x/y)
    | _ -> None


divideSafe 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 IsSome, IsNone for this check. If IsNone yields false, you can safely access the value as option.Value. The following is another way of accessing the value with pattern matching.

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)