Peter Goodman bio photo

Peter Goodman

A software engineer and leader living in Auckland building products and teams. Originally from Derry, Ireland.

Twitter Google+ LinkedIn Github

I came across a pretty annoying problem to solve in WCF today. Suppose you have a custom collection of items you wish to use in a WCF contract but it also has extra properties that you have added, for example change tracking.

    [Serializable]

    public class DtoCollection<T> : List<T>

    {

        private List<T> addedItems;

        private List<T> removedItems;

    }

 

It will serialize the collection fine but your added properties and fields will not appear. The [CollectionDataContract] attribute will not help you. If you look at this really great post from Sowmy Srinivasan's blog you can see the order of preference for WCF serialization markup. So in the case above you can implement IXmlSerializable to customize the serialization and deserialization of your custom collection. I originally found this solution on David Foderick's blog - OnMaterialize(), but the link seems to be down at the moment. I'll not repost the code here but google cache should still have it at this link.