Serializing Immutable Collections in .NET

The serialization story for .NET’s immutable collections is currently less than ideal. When you tag a property of type ImmutableList<T> with the DataMember attribute, the standard deserializer appears to ignore it. There are no runtime errors, the data is just not there.

You can make the property an IList to prevent the data loss, but this leads to a semantic issue. Though you can store an immutable list in an IList, the practice is frowned upon because most people assume that a given IList is not going to marked are read-only. Furthermore, the type checker can’t help catch this mistake at compile time.

To fix the semantic problem one would assume that offering a property of type IReadOnlyList could be used instead. Unfortunately this throws an exception during serialization unless the KnownType attribute is added. And once it is added we’re back to the silent failure to deserialize the property.

Yes. First of all, binary serialization isn't support in the portable subset we are using (visualstudio.uservoice.com/.../3701316-make-the-new-immutable-collection-types-serializab). Secondly, we prefer a model where serialization is done outside the core data structures because it makes it more resilient to implementation changes and solves the cross version serialization when used in client/server scenarios. Popular serialization libraries already plan on adding support for immutable collections, e.g. JSON.NET, protobuf-net.

The trunk of protobuf-net (r666) now has support for immutable lists, arrays, dictionaries, hash-sets, sorted-sets, sorted-dictionaries - and all of their interface twins. But all in a single pattern recognition block.