Imagine this is my scenario:
public abstract class Foo
{
public abstract int X { get; set; }
}
public class FooA : Foo
{
public override int X { get; set; }
public int Y { get; set; }
}
public class FooB : Foo
{
public override int X { get; set; }
public int Z { get; set; }
}
This is a service where I've got some objects to serialize.
public class FooService
{
public List<Foo> GetModels()
{
return new List<Foo>()
{
new FooA() { X = 3, Y = 6 },
new FooB() { X = 5, Z = 10 }
};
}
}
And this is the method where I can't serialize my objects, it throws an exception. I want to serialize derived classes.
private void SerializeObjects()
{
FooService service = new FooService();
var a = service.GetModels();
XmlSerializer x = new XmlSerializer(a.GetType());
TextWriter writer = new StreamWriter("A.xml");
x.Serialize(writer, a);
writer.Close();
}