Skip to content

Chapter 5. Serialization.

October 20, 2009

1. How to serialize an object.

In order to be able to serialize type it needs to be marked with [Serialized] attribute.

[Serializable]
class ObjectToBeSerialized
{
}

 

We can serialize such object like this:

  1: using System;
  2: using System.IO;
  3: using System.Runtime.Serialization.Formatters.Binary;
  4:
  5: [Serializable]
  6: class ObjectToBeSerialized
  7: {
  8: }
  9:
 10: class Program
 11: {
 12:     void Serialize()
 13:     {
 14:         ObjectToBeSerialized instance = new ObjectToBeSerialized();
 15:
 16:         using (FileStream stream = File.Create( @"c:/output.bin"))
 17:         {
 18:             BinaryFormatter formatter = new BinaryFormatter();
 19:             formatter.Serialize(stream, instance);
 20:         }
 21:     }
 22: }

2. How to deserialize object.

  1:
  2: using (FileStream stream = File.Open(@"c:/output.bin", FileMode.Open))
  3: {
  4:     BinaryFormatter formatter = new BinaryFormatter();
  5:     ObjectToBeSerialized instance = (ObjectToBeSerialized )formatter.Deserialize(stream);
  6: }
  7: 

3. How to handle values that are calculated / do not have to be serialized.

  1: using System.Runtime.Serialization;
  2: using System;
  3:
  4: [Serializable]
  5: class ObjectToBeSerialized : IDeserializationCallback
  6: {
  7:     private int m_value1;
  8:
  9:     [NonSerialized]
 10:     private int m_value2;
 11:
 12:     public ObjectToBeSerialized( int _value1)
 13:     {
 14:         m_value1 = _value1;
 15:         m_value2 = 10; // calculated value
 16:     }
 17:
 18:     public void OnDeserialization(object sender)
 19:     {
 20:         m_value2 = 10;
 21:     }
 22: }
 23: 

If we don’t want some fields to be serialized we mark them with [NonSerialized].

If we have some values that are not serialized but have to be initialized we can use IDeserializationCallback interface to handle that.

4. Serialization and version compatibility.

Advertisement

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.