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.

Deserializing Objects

To convert serialized information back to objects, you can call the formatter's Deserialize method. This method accepts a single argument containing the stream that will provide the data. The method returns an object that can be cast to the desired type.

The following code demonstrates deserialization by opening the previously created file and reusing the same binary formatter. Note that the output contains both the public property and private field values that were serialized earlier.

Car car2;
using (FileStream stream = new FileStream(@"c:\Test\car.bin", FileMode.Open))
{
    car2 = (Car)formatter.Deserialize(stream);
}
Console.WriteLine(car2);    // Outputs "Red Coupe, 1 crash(es)."

Common Serialization Problems

There are several common problems reported when using serialization. Often, when calling the Serialize method, an exception similar to that shown below is thrown:

'Test.Car' in Assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
is not marked as serializable.

This exception indicates that a [Serializable] attribute is missing. If you see the exception, check that your class has the attribute set. If it does, check that all fields and properties use types that are serializable. Finally, if you are working with classes in inheritance relationships and are serializing a base type, make sure that subclasses that may be substituted with the base class are also marked as serializable.

A second commonly experienced problem is that the constructor for an object is not executed when data is deserialized. You should ensure that code in the constructor is not essential in this scenario.

23 May 2010