Freigeben über


Serialization Methods for Collections

What methods do I need to implement to have data serialized and deserialized for a collection?

Serialization considers there to be three primary types of collections: dictionary-based collections, list-based collections, and plain old collections (everything else that’s enumerable). That’s also the order in which a type is checked for collection support.

Serialization then needs to search for a way to enumerate the collection contents for serialization and a way to add items to the collections for deserialization. These are the collection’s enumerate and add methods. The enumerate and add methods are based on the primary type of the collection.

A dictionary-based collection supports enumeration through its key-value pairs and addition through a method called Add. These methods are generic when the dictionary is generic (and not when it’s not).

A list-based collection supports enumeration of its values through their direct type and again addition through a method called Add. Like dictionaries, these methods are generic when the list is generic (and not when it’s not). Although Add is defined directly on the non-generic IList, it is actually inherited from the base collection type for the generic IList. Therefore, in the generic world, basic collections can function more like lists.

A plain old collection supports enumeration of its values through their direct type (thus making IEnumerable a particularly plain collection) but somewhat lacks an equivalent to Add. In order to deserialize one of these collections you need to have defined your own Add method with the appropriate parameter type (depending on if the collection is generic or not).