Serializing XML Lists of Abstract Types

 

This is a common problem:

public class ConcreteClass : AbstractClass
{
  public string Name { get; set; }
}

public abstract class AbstractClass
{
  public DateTime DateTime { get; set; }
}

You won't be able to Serialize a list of this type:

      List list = new List();
      ConcreteClass c1 = new ConcreteClass();
      list.Add(c1);




      XmlSerializer serializer = new XmlSerializer(typeof(List));
      TextWriter textWriter = new StreamWriter(@"C:\list.xml");
      serializer.Serialize(textWriter, list);
      textWriter.Close();

you'll get the error

The type Serialize.ConcreteClass was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

I found the solution on StackOverflow and have created a project that shows you how to use it.

Files:

/media/1065/serialize.zip
Share