Free mag vol1 | Page 847

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION public interface IFormatter { ... object Deserialize(Stream serializationStream); void Serialize(Stream serializationStream, object graph); } Recall that the System.Object represents a complete tree of objects. Given this, if you pass in an object that has been marked as [Serializable] and contains other [Serializable] objects, the entire set of objects is persisted in a single method call. As luck would have it, most of the types you find in the System.Collections and System.Collections.Generic namespaces have already been marked as [Serializable]. Therefore, if you would like to persist a set of objects, simply add the desired set to the container (such as a normal array, an ArrayList or a List) and serialize the object to your stream of choice. Now assume that you want to update the JamesBondCar class with a two-argument constructor, so you can set a few pieces of state data (note that you add back the default constructor as required by the XmlSerializer). [Serializable, XmlRoot(Namespace = "http://www.MyCompany.com")] public class JamesBondCar : Car { public JamesBondCar(bool skyWorthy, bool seaWorthy) { canFly = skyWorthy; canSubmerge = seaWorthy; } // The XmlSerializer demands a default constructor! public JamesBondCar(){} ... } With this, you can now persist any number of JamesBondCars: static void SaveListOfCars() { // Now persist a List of JamesBondCars. List myCars = new List(); myCars.Add(new JamesBondCar(true, true)); myCars.Add(new JamesBondCar(true, false)); myCars.Add(new JamesBondCar(false, true)); myCars.Add(new JamesBondCar(false, false)); us