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();

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

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.