Custom Serialization

Sometimes, the default automatic serialization provided by the Serializable attribute is insufficient. Perhaps the object state contains sensitive information, such as a credit card number. In that case, you may want to encrypt the state instead of using a plain by-value serialization. Some other examples that might require custom serialization solutions are if you have some internal knowledge of how to serialize the event subscribers, if which members get serialized depends on the state of the object, or if you want to perform additional proprietary initialization steps during deserialization.

The ISerializable Interface

.NET provides an easy-to-use mechanism for custom serialization that extends the serialization infrastructure. To provide custom serialization and deserialization behavior, you need to implement the ISerializable interface, defined in the System.Runtime.Serialization namespace:

    public interface ISerializable
    {
       void GetObjectData(SerializationInfo info,StreamingContext context);
    }

Every time a client serializes an object, .NET reflects the object’s metadata to see whether the serializable object implements ISerializable. If it does, .NET calls GetObjectData() to retrieve the object’s state. At this point, it’s up to the object to provide the state information in whichever way it wants. You will see an example of implementing ISerializable shortly.

To support the matching custom deserialization, the object must provide a special parameterized custom ...

Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.