Serialization: System.Runtime.Serialization

< BACK  NEXT >
[oR]

Objects commonly have state. An instance of a class, for example, can have one or more fields, each of which contains some value. It's often useful to extract this state from an object, either to store the state somewhere or to send it across a network. Performing this extraction is called serializing an object, while the reverse process, recreating an object from serialized state, is known as deserializing.[1]

[1] This is also sometimes referred to as rehydrating an object.

Serialization extracts an object's state

The .NET Framework class library provides support for serialization. The work of serialization is done by a particular formatter; each formatter provides a Serialize and Deserialize method. The NET Framework class library provides two varieties of formatter. The binary formatter, implemented by the BinaryFormatter class in the System.Runtime.Serialization.Formatters.Binary namespace, serializes an object into a straightforward binary form designed to be compact and quick to parse. The SOAP formatter, implemented by the SoapFormatter class in the System.Runtime.Serialization.Formatters.Soap namespace, serializes an object into a SOAP message like those shown in Chapter 2.

A formatter can be used to serialize an object

Figure 5-1 illustrates the serialization process. As the figure shows, an instance of a class can be run through a formatter that extracts the state of this object in a particular form. As just stated, the binary formatter emits that state information in a simple and compact form, while the SOAP formatter generates the same information wrapped in XML and formatted as a SOAP message. While the outputs shown in the figure are simplified the binary formatter actually stores integers in binary form, for instance they illustrate the key difference between the two serialization options built into the .NET Framework class library.

Figure 5-1. The System.Runtime.Serialization namespace provides two different formatters to serialize an object's state.
graphics/05fig01.gif

Both a binary formatter and a SOAP formatter are provided

When a formatter serializes an object, the resulting state is placed into a stream. As described in the previous section, a stream is an abstraction of a sequence of bytes and so can hold any serialization format. Once it's in a stream, an object's state can be stored on disk (or in the jargon of objects, be made persistent), sent across a network to another machine, or used in some other way.

An object's state is serialized into a stream

For a type to be serializable, its creator must mark it with the Serializable attribute, as Figure 5-1 illustrates. The Serializable attribute can be assigned to classes, structures, and other types or just to specific fields within a type to indicate that only they should be serialized. Also, a type marked with the Serializable attribute can indicate that certain fields should not be saved when an instance of this type is serialized by marking them with the NonSerialized attribute.

Not every type is serializable

Here's a simple VB.NET example that shows how serialization works:

 Imports System Imports System.IO Imports System.Runtime.Serialization Imports _     System.Runtime.Serialization.Formatters.Binary Module SerializationExample     <Serializable()> Class Employee         Public Name As String         Public Age As Integer     End Class     Sub Main()         Dim E1 As Employee = New Employee()         Dim E2 As Employee = New Employee()         Dim FS As FileStream         Dim BinForm As BinaryFormatter = _             New BinaryFormatter()         E1.Name = "Bob"         E1.Age = 36         FS = File.Create("test.dat")         BinForm.Serialize(FS, E1)         FS.Close()         FS = File.Open("test.dat", FileMode.Open)         E2 = BinForm.Deserialize(FS)         Console.WriteLine("E2 Name: {0} ", E2.Name)         Console.WriteLine("E2 Age: {0} ", E2.Age)     End Sub End Module 

This example begins with several Imports (using) statements. As always, these statements aren't required, but they make the code that follows more readable by removing the need to type fully qualified names. Following these, the module begins with the definition of a very simple Employee class. This class contains just two fields representing an employee's name and age and has no methods at all. (This is unrealistic, of course, but information about methods isn't stored anyway when a class is serialized.)

The example's Sub Main routine creates two instances of the Employee class, E1 and E2, and then declares a FileStream called FS. It next creates an instance of the BinaryFormatter class that will be used to serialize and deserialize the objects' state. Once that state has been created by initializing E1's fields to contain a name and an age, the file test.dat is created to hold the serialized state. The binary formatter's Serialize method is then called, which serializes the state in E1 into the stream FS. When the stream is closed, its contents are written to the file test.dat.

The example then reopens test.dat, associating it once again with the stream FS. This stream is passed into the binary formatter's Deserialize method, with the result assigned to E2. Although E2 has had just its default state so far, the deserialization process gives it the state that was extracted earlier from E1. Accordingly, the output of this simple program is

 E2 Name: Bob E2 Age: 36 

Serialization can also be customized. For example, if a class implements the ISerializable interface, it can participate in its own serialization. This interface has only a single method that allows controlling the details of what gets serialized. Also, although it's not shown in this simple example, serializing an object will also serialize objects it refers to, causing them all to be serialized (or deserialized) at once. And for the brave of heart, it's possible to build your own formatter that does serialization in a completely customized way by inheriting from the abstract class System.Runtime.Serialization.Formatter. However it's done, serialization is useful, and in its basic form, at least, it's simple to use. As described later in this chapter, serialization plays a role in several parts of the .NET Framework class library.

Serialization has options

< BACK  NEXT >


Understanding. NET. A Tutorial and Analysis
Understanding .NET: A Tutorial and Analysis (Independent Technology Guides)
ISBN: 0201741628
EAN: 2147483647
Year: 2002
Pages: 60

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net