Serialize generics list part 2



This post is the 3rd of series on serialization in WCF.

The post is taking the previous post concept one step ahead by wrapping the List<T> as serializable type

Downloads available here

Jump into the code

see the theory in the previous post

[XmlRoot (Namespace = “htp://…”)]
public class GenListCustom<T>:List<T>,IXmlSerializable {
private static readonly string ITEM_ELEMENT_NAME=
typeof (T).Name;

XmlSchema IXmlSerializable.GetSchema() {
throw new NotImplementedException();

void IXmlSerializable.ReadXml(XmlReader reader){
var ser=new DataContractSerializer(typeof(T));

while(reader.Name == ITEM_ELEMENT_NAME){
var item = (T)ser.ReadObject(reader);
this.Add (item);

void IXmlSerializable.WriteXml ( XmlWriter writer ) {
var ser = new DataContractSerializer (typeof (T));

writer.WriteStartElement (“Items”, “htp://…”);
foreach (var item in this) {
ser.WriteObject (writer, item);
writer.WriteEndElement ();

Actually this class is identical to the class on our previous post with one exception, it use T instead of CompositeType.

WCF and generics collections

Unfortunately WCF does not always handling well generics collections of complex types (despite the fact that it can be serialized using Data Contract serialization).

In those case you may use the the technique of having the collection as composite type and using property decorated with DataMember attribute in order to serialize the collection (as discuss in Serialize generics list part 1)


I used post reuse pattern ๐Ÿ™‚ leaving the theory in the previous post, but after reading the previous post I believe itโ€™s kind of straight forward.

As Rotem suggest in his comment you should consider using the CollectionDataContract attribute.

Downloads available here

Previous Posts Tags:

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



  1. Rotem Bloom2009/06/09 ื‘ 09:05

    why not use the CollectionDataContract attribute?

  2. bnaya2009/06/09 ื‘ 11:53

    Rotem has very good point
    as long as you don’t need advance xml serialization
    it is more reasonable to use CollectionDataContract

    in cases like using WCF service from the compact framework (which support xml serialization but does not support Data Contract serialization) if you need advance serialization i.e. using IXmlSerializable you may need this technique