Collections without CollectionDataContract

In the article about serialization conflicts, one of the points mentioned was that CollectionDataContract doesn’t let you add non-default data members. How do I format a collection that contains data members? CollectionDataContract is automatically being added even if I don’t want it.

The trick is that CollectionDataContract is automatically applied to the default collection implementations rather than to all collections. That means that if your class is a List of T then you’ll get the automatic CollectionDataContract behavior. If your class is an IList of T then you can choose to decorate the type with normal data contracts.

This subtle distinction allows you to save the day. Convert your collection type to implement the corresponding interface and delegate all of the calls to a concrete implementation of the collection that you keep as a member variable. Then, you can figure out how to serialize that member variable, which gives you full control over how the list elements mix together with the other data members.

Next time: Printing Flexible Message Headers

Comments (3)

  1. Semedao says:

    Hi Nicholas,

    I try to do it with my class that inherit from generic Dictionary and it throw exception

    ‘ cannot be ISerializable and have DataContractAttribute attribute’…

    (Generic dictionary implement ISerializable)

    So , out of encapsulate the custom dictionary class inside other class that wilkl hold my data members , there is other work around ?

  2. How do I detect when the other side of a TCP connection has gone away? Does TCP keep-alive take care

  3. Hi Semedao,

    As the article describes, the way to take control back from the serializer is to inherit from IDictionary and hold the actual Dictionary as a member.