Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata