WCF: Sending Collections Over the Wire

Recently I needed to send a custom collection class as a response to a WCF call.  I duly added the normal [DataContract] attribute and was rewarded with the following WCF error:

Type 'MyCollection' is an invalid collection type since it has DataContractAttribute attribute.

Hang on, you may think, why do we needed custom collection classes given all the great generic collections in .Net 2.0, e.g. List<T> and so on?  You have a point, but for reasons of their own some of my team members decided to create a class such as the following:

public class MyCollection : List<MyObject>

It turns out that [DataContract] is not the correct attribute to be using in this case.  WCF also provides a [CollectionDataContract] attribute.  So the following code works just fine:

public class MyCollection : List<MyObject>

October 24 2006
blog comments powered by Disqus