Serializing Generics

We had a quick discussion at work here about using the XmlSerializer on a Generic collection, so I threw together a quickie example.

Our "Business Entity":

[System.Serializable()]
public class Entity {
    public string Name;
    public DateTime DOB;

    public Entity() { }
    public Entity(string name, DateTime dob) {
        Name = name;
        DOB = dob;
    }
}

Create a Generic list of our new Entity object:

System.Collections.Generic.List<Entity> ppl = new List<Entity>();
ppl.Add(new Entity("Rob", new DateTime(1974, 12, 16)));
ppl.Add(new Entity("Joe", new DateTime(1978, 12, 16)));

Now Serialize it, using the XmlSerializer:

System.Xml.Serialization.XmlSerializer xser =
    new System.Xml.Serialization.XmlSerializer(typeof(List<Entity>));

System.Text.StringBuilder sb = new StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
xser.Serialize(sw, ppl);
Console.Write(sb.ToString());

Now if we're trying to talk SOAP with the SoapSerializer then thats a different story, take this example:

System.IO.MemoryStream stm = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Soap.SoapFormatter soapSer = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
soapSer.Serialize(stm, ppl);
stm.Position = 0;
Console.Write(System.Text.Encoding.Default.GetString(stm.ToArray()));

It wont even make it by the soapSer.Serialize() method.  Thows a "Soap Serializer does not support serializing Generic Types" exception.

 

4 Comments

Comments have been disabled for this content.