Serialize Objects in VB.NET
.NET makes it easy to store an object's state.
by Billy Hollis
VSLive! Orlando, September 18, 2002
Note: Billy Hollis is presenting "Objects in the Real World" at VBITS Orlando, Wednesday, September 18. This tip is from that session. The session will also cover other real-world techniques for object programming, such as using the Shadows keyword to patch object interfaces and how to load forms and classes that were not available when a project was compiled.
As long as we've been working with objects, we've had a need to store a representation of them. Perhaps we know an object will not be needed for a while, and we don't want it cluttering up memory in the meantime. Or we might need to transfer an instance of an object from one system to another.
For all such cases, the state of the object needs to be represented in some form that can be stored indefinitely, or passed to another system. You usually do this by storing the object's state information as a series of bytes of data.
The process of storing the state of an object is called "serialization." Using this state information to create a new, equivalent object instance is called "deserialization." In VB6 and earlier versions, you had to write your own logic to carry out these operations. But, as with so many routine programming tasks, serialization is automated in .NET.
If you merely place a <Serializable()> attribute at the top of a class, an object instance automatically has the capability to be serialized. You place this attribute on the declaration for the class, like this:
<Serializable()> _
Public Class MyClassName
You can also make an object serializable by implementing an interface called ISerializable, but this is a lot more work. For most common purposes, using the <Serializable()> attribute is easier and just as effective.
Once a class has been marked with the <Serializable()> attribute, it can then have its state stored. If you use another class called a Formatter, you can save the state of a .NET object instance as a series of bytes, which can then be stored on disk or in a database, or transferred from one system to another using .NET Remoting or message queues. Another Formatter class can then "reconstitute" the object instance from the serialized state information.
There are different Formatter classes for different types of serialization. The BinaryFormatter saves all the internal state of an object, including private variables. This is called "deep" serialization." The XMLFormatter saves only public properties and data members, in a process called "shallow serialization." There are additional formatters for other purposes. Which you use depends on whether your objects have internal state information that is necessary in the reconstituted object instance, and what you intend to do with the serialized information.
Back to top
|