O'Reilly logo

Object-Oriented Programming with Visual Basic .NET by J.P. Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.5. Custom Serialization

Only public, read/write fields are serialized to XML, while binary serialization puts everything but the kitchen sink into the stream. Does this seem a little extreme? If more control is needed or if the default behavior doesn't do what needs to be done, the ISerializable interface provides an object with the means to control its own serialization. Implementing the interface is surprisingly simple. The interface contains a single method, called GetObjectData, with the following signature:

Sub GetObjectData(ByVal info As SerializationInfo, _
                  ByVal context As StreamingContext)

8.5.1. SerializationInfo

As shown in Example 8-14, the first parameter to the GetObjectData method is a class called SerializationInfo that contains a method named AddValue. AddValue is overloaded to take all the native types from the System namespace, including Object and Type. Just pass it the data that needs to be serialized. Data is passed as a key-value pair so that values can be retrieved in any order (by name) during deserialization. Anything can be added to the stream, and additional business logic is easily incorporated.

Example 8-14. Implementing ISerializable, Part I
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
   
<Serializable( )> _
Public Class Employee
    Implements ISerializable
   
    Private Sub GetObjectData(ByVal info As SerializationInfo, _
						ByVal context As StreamingContext) _
						Implements ISerializable.GetObjectData ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required