CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
Customizing Serialization Using Attributes
Although implementing the ISerializable interface is one way to customize the serialization process,
the preferred way to customize the serialization process since the release of .NET 2.0 is to define
methods that are attributed with any of the new serialization-centric attributes: [OnSerializing],
[OnSerialized], [OnDeserializing], or [OnDeserialized]. Using these attributes is less cumbersome
than implementing ISerializable because you do not need to interact manually with an incoming
SerializationInfo parameter. Instead, you can modify your state data directly, while the formatter
operates on the type.
Note You can find these serialization attributes defined in the System.Runtime.Serialization namespace.
When you define method decorated with these attributes, you must define the methods so they
receive a StreamingContext parameter and return nothing (otherwise, you will receive a runtime
exception). Note that you are not required to account for each of the serialization-centric attributes, and
you can simply contend with the stages of serialization you want to intercept. The following snippet
illustrates this. Here, a new [Serializable] type has the same requirements as StringData, but this time
you account for using the [OnSerializing] and [OnDeserialized] attributes:
[Serializable]
class MoreData
{
private string dataItemOne = "First data block";
private string dataItemTwo= "More data";
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
// Called during the serialization process.
dataItemOne = dataItemOne.ToUpper();
dataItemTwo = dataItemTwo.ToUpper();
}
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
// Called when the deserialization process is complete.
dataItemOne = dataItemOne.ToLower();
dataItemTwo = dataItemTwo.ToLower();
}
799