Friday, May 11, 2007

Simple Serialization and Deserialization in C#

.NET provides a functionality for storing and loading objects. This post shows how it can be used. The mechanism is called serialization and its purpose is to convert any object to stream of bytes that can be saved on a disk, sent by a protocol via internet etc.

So, at the beginning you have a class which you want to serialize. For example it looks like this:

public class MyExampleClass


  public string name;

  public int age;

  public readonly DateTime dateOfBirth;

  public double[] score;

  public MyExampleClass(string name, int age, DateTime dateOfBirth)

  { = name;

    this.age = age;

    this.dateOfBirth = dateOfBirth;

    this.score = new double[0];



Now, you want to save object of this class on a disk. At first add some namespaces:

using System.IO;    //Stream class

using System.Runtime.Serialization.Formatters.Binary;

Add [Serializable] attribute to your class:


public class MyExampleClass

and then add methods for save and load in MyExampleClass:

public void SaveToFile(string filename)


  using (Stream stream = File.Open(filename, FileMode.Create))


    BinaryFormatter formatter = new BinaryFormatter();

    formatter.Serialize(stream, this);




public static MyExampleClass LoadFromFile(string filename)


  using (Stream stream = File.Open(filename, FileMode.Open))


    BinaryFormatter formatter = new BinaryFormatter();

    return (MyExampleClass)formatter.Deserialize(stream);



Here is an example how to use these methods:

//create new object

MyExampleClass myObject = new MyExampleClass("John", 30, new DateTime(1967, 1, 1));

myObject.score = new double[] { 5.5, 5.6, 6.1 };



myObject = null; //discard object


//load saved object

myObject = MyExampleClass.LoadFromFile("store");


That is all. It is very simple to use.

Note: Instead of BinaryFormatter you can use SoapFormatter.
The code is the same, only replace BinaryFormatter by SoapFormatter and use System.Runtime.Serialization.Formatters.Soap namespace. For this namesapce you have to add reference to System.Runtime.Serialization.Formatters.Soap.dll assembly in your project.

The difference is in the saved file. With SoapFormatter you get a file that is human readable. For our example, the saved file contains:

<a1:MyExampleClass id=\"ref-1\">

  <name id=\"ref-3\">John</name>





  <score href=\"#ref-4\"/>


<SOAP-ENC:Array id=\"ref-4\" SOAP-ENC:arrayType=\"xsd:double[4]\">





Notice how the reference-typed objects are stored.

Anyone can change the content of this file and the object will reflect these changes after deserialization.

kick it on

No comments: