Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

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

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# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata