F# Option types Using Option types from C#


It is not a good idea to expose Option types to C# code, as C# does not have a way to handle them. The options are either to introduce FSharp.Core as a dependency in your C# project (which is what you'd have to do if you're consuming an F# library not designed for interop with C#), or to change None values to null.

Pre-F# 4.0

The way to do this is create a conversion function of your own:

let OptionToObject opt =
    match opt with
    | Some x -> x 
    | None -> null

For value types you'd have to resort to boxing them or using System.Nullable.

let OptionToNullable x = 
    match x with 
    | Some i -> System.Nullable i
    | None -> System.Nullable ()

F# 4.0

In F# 4.0, the functions ofObj, toObj, ofNullable, and toNullable where introduced to the Option module. In F# interactive they can be used as follows:

let l1 = [ Some 1 ; None ; Some 2]
let l2 = l1 |> List.map Option.toNullable;;

// val l1 : int option list = [Some 1; null; Some 2]
// val l2 : System.Nullable<int> list = [1; null; 2]

let l3 = l2 |> List.map Option.ofNullable;;
// val l3 : int option list = [Some 1; null; Some 2]

// Equality
l1 = l2 // fails to compile: different types
l1 = l3 // true

Note that None compiles to null internally. However as far as F# is concerned it is a None.

let lA = [Some "a"; None; Some "b"]
let lB = lA |> List.map Option.toObj

// val lA : string option list = [Some "a"; null; Some "b"]
// val lB : string list = ["a"; null; "b"]

let lC = lB |> List.map Option.ofObj
// val lC : string option list = [Some "a"; null; Some "b"]

// Equality
lA = lB // fails to compile: different types
lA = lC // true