Oldrich Svec
Oldrich Svec

Reputation: 4231

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)

Upvotes: 0

Views: 482

Answers (2)

eirik
eirik

Reputation: 708

Try using a different serializer, like NetDataContractSerializer. From what I know BinaryFormatter is being considered as legacy and has a few other issues too, for instance this.

Upvotes: 1

John Palmer
John Palmer

Reputation: 25516

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

Upvotes: 2

Related Questions