// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace E { public abstract class Person { private string name; public Person() : this("") // to avoid null { } public Person(string name) { this.name = name; } public string Name { get { return name; } set { name = value; } } } public class Student : Person { private string college; public Student() : this("", "") // to avoid null { } public Student(string name, string college) : base(name) { this.college = college; } public string College { get { return college; } set { college = value; } } } public class XMLSerialization { public static void XMLSerialize(string filePath, T obj, Type[] additional) // addd the additional types needed { try { using (FileStream fs = new FileStream(filePath, FileMode.Create)) { XmlSerializer XmlSer = new XmlSerializer(typeof(T), additional); XmlSer.Serialize(fs, obj); } } catch(Exception ex) { Console.WriteLine(ex); // **** NEVER EVER JUST EAT THE EXCEPTION !!!! **** } } } public class Program { public static void Main(string[] args) { List myListNotWork1 = new List(); Person p1 = new Student("olle", "sundsta"); myListNotWork1.Add(p1); XMLSerialization.XMLSerialize(@"C:\z1.xml", myListNotWork1, new Type[] { typeof(Student) }); // infer T and add Student as additional type List myListNotWork2= new List(); Student s1 = new Student("olle", "sundsta"); myListNotWork2.Add(s1); XMLSerialization.XMLSerialize(@"C:\z2.xml", myListNotWork2, new Type[] { typeof(Student) }); // infer T and add Student as additional type List myListWork = new List(); Student s2 = new Student("olle", "sundsta"); myListWork.Add(s2); XMLSerialization.XMLSerialize(@"C:\z3.xml", myListWork, new Type[0]); // infer T and add no additional type } } }