serializationf#option-typebinaryformatter

Serialization of Option / None by BinaryFormatter throws ArgumentNullException using F#


How do I serialize None in F#? The following code throws an System.ArgumentNullException: Object Graph cannot be null. error:

let f = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
let m = System.IO.MemoryStream()
f.Serialize (m, None)

Solution

  • For some performance reasons, the compiler often will make None = null. I think the best solution is then to wrap the whole thing in an extra layer of Option

    like this

    let f = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
    let m = System.IO.MemoryStream()
    f.Serialize (m,Some( None))
    

    Then you just remove that extra Some when you deserialize