© 2004 Microsoft Corporation. All rights reserved.
Figure 1 Serializing an Object Graph
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
•••
MemoryStream SerializeToMemory(Object objGraph) {

   // Construct a stream that is to hold the serialized objects
   MemoryStream stream = new MemoryStream();

   // Construct a serialization formatter that does all the hard work
   BinaryFormatter formatter = new BinaryFormatter();

   // Tell the formatter to serialize the objects into the stream
   formatter.Serialize(stream, objGraph);

   // Return the stream of serialized objects back to the caller
   return(stream);
}
Figure 2 Deserializing a Memory Byte Stream
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
•••
Object DeserializeFromMemory(Stream stream) {

   // Construct a serialization formatter that does all the hard work
   BinaryFormatter formatter = new BinaryFormatter();

   // Tell the formatter to deserialize the objects from the stream
   return(formatter.Deserialize(stream));
}
Figure 3 DeepClone
Object DeepClone(Object original) {

   // Construct a temporary memory stream
   MemoryStream stream = new MemoryStream();

   // Construct a serialization formatter that does all the hard work
   BinaryFormatter formatter = new BinaryFormatter();

   // This line is explained in the "Streaming Contexts" section
   formatter.Context = new StreamingContext(
      StreamingContextStates.Clone);

   // Serialize the object graph into the memory stream
   formatter.Serialize(stream, original);

   // Seek back to the start of the memory stream before deserializing
   stream.Position = 0;

   // Deserialize the graph into a new set of objects
   // and return the root of the graph (deep copy) to the caller
   return(formatter.Deserialize(stream));
}
Figure 4 Not Serializable
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

struct Point {
   public Int32 x, y;

   public Point(Int32 x, Int32 y) {
      this.x = x;
      this.y = y;
   }
}

class App {
   public static void Main() {
      MemoryStream stream = new MemoryStream();
      BinaryFormatter formatter = new BinaryFormatter();
      formatter.Serialize(stream, new Point(1, 2));
     •••
   }
}
Figure 5 Modified Circle Type
[Serializable]
class Circle : IDeserializationCallback {
   Double radius;

   [NonSerialized]
   public Double area;

   public Circle(Double radius) {
      this.radius = radius;
      area = Math.PI * radius * radius;
   }

   void IDeserializationCallback.OnDeserialization(Object sender) {
      area = Math.PI * radius * radius;
   }
}

Home
Topics
Issues
Columns
Downloads
Subscribe
Contact Us

MSDN Magazine