Explicit Serialization

Consider a case in which a client wants to serialize a complex graph of objects to a file on disk. Furthermore, let’s assume that the objects already support serialization (if not, the client’s job is much harder). Fundamentally, there are two things the client needs to initiate an explicit serialization: an object reference identifying the root of the object graph, and a Stream reference identifying the place to serialize the object graph to.

Given these two references, the client needs some way to initiate the serialization and deserialization process. Since this is a common need, the Framework defines a standard interface called IFormatter that provides Serialize and Deserialize methods that work in terms of object and Stream references.

The Framework also provides two concrete implementations of this interface: the BinaryFormatter class (which lives in the System.Runtime.Serialization.Formatters.Binary namespace, and serializes object graphs using a binary format), and the SoapFormatter class (which lives in the System.Runtime.Serialization.Formatters.Soap namespace, and serializes object graphs as XML using SOAP Section 5 encoding rules).

Using these classes, clients can serialize graphs of objects with almost no code:

public void SerializeGraph(string file, object root) {
  Stream stm = new FileStream(file, FileMode.Create);  
  IFormatter fmt = new BinaryFormatter( );  
  fmt.Serialize(stm, root);
  stm.Flush( );
  stm.Close( );
}

When passed a target filename and the ...

Get C# in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.