Serialization Events

.NET 2.0 introduces support for serialization events. .NET calls designated methods on your class when serialization and deserialization take place. Four serialization and deserialization events are defined. The serializing event is raised just before serialization takes place, and the serialized event is raised just after serialization. Similarly, the deserializing event is raised just before deserialization, and the deserialized event is raised after deserialization. Both classes and structures can take advantage of serialization events. You designate methods as serialization event handlers using method attributes, as shown in Example 9-9.

Example 9-9. Applying the serialization event attributes

[Serializable]
public class MyClass
{
   [OnSerializing]
   void OnSerializing(StreamingContext context)
   {...}
   [OnSerialized]
   void OnSerialized(StreamingContext context)
   {...}
   [OnDeserializing]

   void OnDeserializing(StreamingContext context)
   {...}
   [OnDeserialized]
   void OnDeserialized(StreamingContext context)
   {...}
}

Note that the class itself must still be marked for serialization. Each serialization event-handling method must have the following signature:

    void <Method Name>(StreamingContext context);

This is required because internally .NET still uses delegates to subscribe and invoke the event-handling methods. If the attributes are applied on methods with incompatible signatures, .NET will throw a SerializationException.

StreamingContext is a structure informing the ...

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.