Skip to content

Serialization

Mario Gutierrez edited this page Jan 8, 2017 · 24 revisions

Serialization is the process of persisting the state of an object to a file or memory buffer. The persisted data contains all the necessary information you need to reconstruct (deserialize) the state of the object.

Serializable marks a class serializable.

[Serializable]
public class UserPrefs
{
  public string WindowColor;
  public int FontSize;

  [NotSerialized]
  private int passcode;
}

Example using BinaryFormatter to write a Serializable object to a file stream.

UserPrefs userData = new UserPrefs { WindowColor = "Blue", FontSize = 24 };
BinaryFormatter bf = new BinaryFormatter();
using (Stream fs = new File.OpenWrite("user.dat"))
{
  bf.Serialize(fs, userData); 
}

All classes in a hierarchy must be marked as serializable, otherwise using types like BinaryFormatter or SoapFormatter will throw a SerializationException at runtime.

Object Graphs

The CLR accounts for all related objects as well to ensure that the data is persisted correctly. It does this by building an object graph.

(3: Car) -> (2: Radio)  
(1: SpecialCar) -> (3: Car)  
(1: SpecialCar) -> (2: Radio)  

This is one way of representing a graph with three nodes, where: "Car" depends on "Radio", and "SpecialCar" depends on both "Car" and "Radio".

The CLR may represent this as such (specifics not certain from source material):

[Car 3, ref 2], [Radio 2], [SpecialCar 1, ref 3, ref 2] 

Serialization Formatters

.NET provides some types to do serialization.

  • BinaryFormatter in System.Runtime.Serialization.Formatters.Binary
  • SoapFormatter in System.Runtime.Serialization.Formatters.Soap
  • XmlSerializer in System.Xml.Serialization

The first two serialize all fields of an object. The XML formatter, on the other hand, only serializes public fields.

Both the binary and SOAP formatters implement the IFormatter and IRemotingFormatter interfaces.

public interface IFormatter
{
  SerializationBinder Binder { get; set; }
  StreamingContext Context { get; set; }
  ISurrogateSelector SurrogateSelector { get; set; }
  object Deserialize(Stream serializationStream);
  void Serialize(Stream serializationStream, object graph);
}
public interface IRemotingFormatter : IFormatter
{
  object Deserialize(Stream serializationStream, HeaderHandler handler);
  void Serialize(Stream serializationStream, object graph, Header[] headers);
}
Clone this wiki locally