CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
Configuring Objects for Serialization
To make an object available to .NET serialization services, all you need to do is decorate each related
class (or structure) with the [Serializable] attribute. If you determine that a given type has some
member data that should not (or perhaps cannot) participate in the serialization scheme, you can mark
such fields with the [NonSerialized] attribute. This can be helpful if you would like to reduce the size of
the persisted data, and you have member variables in a serializable class that do not need to be
remembered (e.g., fixed values, random values, and transient data).
Defining Serializable Types
To get the ball rolling, create a new Console Application named SimpleSerialize. Insert a new class
named Radio, which has been marked [Serializable], excluding a single member variable (radioID)
that has been marked [NonSerialized] and will, therefore, not be persisted into the specified data
stream.
[Serializable]
public class Radio
{
public bool hasTweeters;
public bool hasSubWoofers;
public double[] stationPresets;
}
[NonSerialized]
public string radioID = "XF-552RR6";
Next, insert two additional class types to represent the JamesBondCar and Car classes, both of which
are also marked [Serializable] and define the following pieces of field data:
[Serializable]
public class Car
{
public Radio theRadio = new Radio();
public bool isHatchBack;
}
[Serializable]
public class JamesBondCar : Car
{
public bool canFly;
public bool canSubmerge;
}
Be aware that you cannot inherit the [Serializable] attribute from a parent class. Therefore, if you
derive a class from a type marked [Serializable], the child class must be marked [Serializable] as
well, or it cannot be persisted. In fact, all objects in an object graph must be marked with the
[Serializable] attribute. If you attempt to serialize a nonserializable object using the BinaryFormatter
or SoapFormatter, you will receive a SerializationException at runtime.
783