BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

Binary Serialization

A standard problem with object-oriented languages is that of persisting object state. Binary serialization allows single objects or complex models to be converted to binary streams, which may be stored in files or transported to other systems.

What is Serialization?

Serialization is the process of converting an object's state into information that can be stored for later retrieval or that can be sent to another system. For example, you may have an object that represents a document that you wish to save. This object could be serialized to a stream of binary information and stored as a file on disk. Later the binary data can be retrieved from the file and deserialized into objects that are exact copies of the original information. As a second example, you may have an object containing the details of a transaction that you wish to send to a non-.NET system. This information could be serialised to XML before being transmitted. The receiving system would convert the XML into a format that it could understand.

The .NET framework supports two styles of serialization. Binary serialization converts objects into binary information. This gives a concise result and ensures that when the data is deserialized, the object structure is correctly reconstructed. Deserialized objects are of the same types as the originating objects and references are recreated. If two child objects originally had the same reference, the deserialized version will also have those child objects sharing a reference. The data generated by binary serialization includes public and private properties and fields.

XML serialization converts the state of objects into XML. This allows the information to be deserialized into different data types, including into software that has been created using technologies other than the .NET framework. As XML documents can be verbose, the serialized information can be larger than its binary equivalent. However, it is human-readable and, in appropriate scenarios, can be easily edited. One important disadvantage of XML serialization is that private properties and fields are not extracted so cannot be recreated from the data. Another disadvantage is that references are not encoded. Deserializing an object that had two child objects with the same reference will generate two separate references.

In this article I will describe how to use binary serialization. XML serialization will be considered in a future article.

Serializing Objects

Basic binary serialization is simple to achieve using the .NET framework. The first requirement is that all classes and structures that may be serialized must be decorated with the Serializable attribute. In addition, all of the types of fields and properties in your class must also be serializable. A sample serializable class containing two public properties and a private field is shown below.

NB: For this example, C# 3.0 automatically implemented property syntax has been used. If you are using an earlier language version, expand these to full property declarations with backing store fields.

[Serializable]
public class Car
{
    private int _crashes = 0;

    public string Model { get; set; }
            
    public string Colour { get; set; }
            
    public void AddCrash()
    {
        _crashes++;
    }

    public override string ToString()
    {
        return string.Format("{0} {1}, {2} crash(es).", Colour, Model, _crashes);
    }
}

We can now create an instance of the Car class to serialize:

Car car = new Car();
car.Colour = "Red";
car.Model = "Coupe";
car.AddCrash();
Console.WriteLine(car);     // Outputs "Red Coupe, 1 crash(es)."

Serialization Classes

The binary serialization process uses classes from the System.Runtime.Serialization and System.Runtime.Serialization.Formatters.Binary namespaces. In the sample code, we will serialize an object and store the resultant information in a file. This uses functionality from the System.IO namespace. To simplify the code for all of the classes used, add the following using directives to the code file.

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

The first object required to perform serialization is a formatter. Formatters are responsible for converting objects to serialized information and they implement the IFormatter interface. To create a binary formatter, add the following line of code:

IFormatter formatter = new BinaryFormatter();

When the formatter is used, the information is sent to a stream. In order that you can easily view the data, we will use a FileStream and store the serialized object in a file. As FileStreams implement the IDisposable interface, we should call the Dispose method when we have finished the process. To do so automatically, we can create the stream within a using statement. The following code creates a FileStream for a file named "car.bin" in the "c:\test" folder. You may wish to change the name and location of the file.

using (FileStream stream = new FileStream(@"c:\Test\car.bin", FileMode.Create))
{
}

With the stream prepared, the Serialize method of the formatter can be executed. This method accepts two arguments. The first is the stream that the serialized information should be sent to. The second is the object to convert. Add the following code between the braces of the using statement.

formatter.Serialize(stream, car);

You can now execute the program. When it completes, the file should have been created.

23 May 2010