CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
You use XmlSerializer here, so you are required to specify type information for each of the
subobjects within the root object (List, in this case). However, the logic would be even
more straightforward if you were to use the BinaryFormatter or SoapFormatter type instead, as shown
here:
static void SaveListOfCarsAsBinary()
{
// Save ArrayList object (myCars) as binary.
List myCars = new List();
}
BinaryFormatter binFormat = new BinaryFormatter();
using(Stream fStream = new FileStream("AllMyCars.dat",
FileMode.Create, FileAccess.Write, FileShare.None))
{
binFormat.Serialize(fStream, myCars);
}
Console.WriteLine("=> Saved list of cars in binary!");
Source Code The SimpleSerialize application is included under the Chapter 20 subdirectory.
Customizing the Soap/Binary Serialization Process
In a majority of cases, the default serialization scheme provided by the .NET platform will be exactly
what you require. Simply apply the [Serializable] attribute to your related types and pass the tree of
objects to your formatter of choice for processing. In some cases, however, you might want to become
more involved with how a tree is constructed and handled during the serialization process. For example,
perhaps you have a business rule that says all field data must be persisted using a particular format, or
perhaps you need to add additional bits of data to the stream that do not map directly to fields in the
object being persisted (e.g., timestamps and unique identifiers).
When you want to become more involved with the process of object serialization, the
System.Runtime.Serialization namespace provides several types that allow you to do so. Table 20-13
describes some of the core types you should be aware of.
Table 20-13. System.Runtime.Serialization Namespace Core Types
794
Type
Meaning in Life
ISerializable
You can implement this interface on a [Serializable] type to control
its serialization and deserialization.
ObjectIDGenerator
This type generates IDs for members in an object graph.
[OnDeserialized]
This attribute allows you to specify a method that will be called
immediately after the object has been deserialized.