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