using System.Collections.Generic;
using System.Xml.Serialization;
public Base Base { get; set; }
public int JustSomePropInBase { get; set; }
public class Derived : Base
public int JustSomePropInDerived { get; set; }
var sampleObject = new Container { Base = new Derived() };
var allTypes = new[] { typeof(Container), typeof(Base), typeof(Derived) };
Console.WriteLine("Trying to serialize without a derived class metadata:");
SetupSerializers(allTypes.Except(new[] { typeof(Derived) }).ToArray());
catch (InvalidOperationException e)
Console.WriteLine("This error was anticipated,");
Console.WriteLine("we have not supplied a derived class.");
Console.WriteLine("Now trying to serialize with all of the type information:");
SetupSerializers(allTypes);
Console.WriteLine("Slides down well this time!");
static void Serialize<T>(T o)
serializerDictionary[typeof(T)].Serialize(Console.Out, o);
private static Dictionary<Type, XmlSerializer> serializerDictionary;
static void SetupSerializers(Type[] allTypes)
var allSerializers = XmlSerializer.FromTypes(allTypes);
serializerDictionary = Enumerable.Range(0, allTypes.Length)
.ToDictionary(i => allTypes[i], i => allSerializers[i]);