BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Serializing Immutable Collections in .NET

Serializing Immutable Collections in .NET

Bookmarks

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.

Likewise the legacy serialization mechanism, which uses the Serializable attribute, isn’t supported. Immo Landwerth writes,

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.

This leaves us with third-party libraries such as JSON.NET. As of version 5.0r7, JSON.NET has support for .NET’s official immutable collections library. Also new in this version is JsonExtensionData, which stores any additional data that isn’t represented by a property on the class being deserialized.

Marc Gravell also announced that protobuf-net will support the immutable collections,

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.

Rate this Article

Adoption
Style

BT