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)

  {

    this.name = 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:

[Serializable]

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.SaveToFile("store");

 

myObject = null; //discard object

 

//load saved object

myObject = MyExampleClass.LoadFromFile("store");

Console.WriteLine(myObject.name);



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>

  <age>30</age>

  <dateOfBirth>

    1967-01-01T00:00:00.0000000+01:00

  </dateOfBirth>

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

</a1:MyExampleClass>

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

  <item>5.5</item>

  <item>5.6</item>

  <item>6.1</item>

</SOAP-ENC:Array>



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

No comments: