Saturday, January 26, 2008

Object serialization using binary formatters in C#

In this article I'll show you the method of serializing a class object on a disk drive in a data file using binary formatters in C#. When we serialize an object, we actually preserve the state of the object on the disk so we can pick its state right from there where we left.

A classic example can be of a video game. For example you're developing a video game and you want to stop and exit the game but you would also like to start playing the game from where you left it. You could achieve this functionality as a game developer to serialize all of your objects on the disk.

We have already seen how we can serialize and deserialize some text using binary formatter in Microsoft.Net in a previous article:
Serialization of data using binary formatters in C#

In this article we're using binary formatter again for serialization but this time we'll serialize an object. You'll need following two namespaces for this purpose.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

First of all we need to define a class which is serializable:

[Serializable]
class Product
{
public int ProductID;
public double Price;
public string Name;


public Product(int _productID, double _price, string _name)
{
ProductID = _productID;
Price = _price;
Name = _name;
}
}

This is a simple product class having attribute Serializable, which makes objects of this class capable of being serialized.

Following code serializes the object of class product on the disk.

Product objProduct = new Product(1,200,'someproduct');
FileStream fs = new FileStream("c:\\productobject.Data", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, objProduct);
fs.Close();

You'll see that when you execute this code it'll create a file with the specified name on the hard drive and will save the object's status in it.

Now, when you want to deserialize the object, that is, you want to load the state of the object in to an object of Product class you'll use following code.

Product objProduct;
FileStream fs = new FileStream("c:\\productobject.Data", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
objProduct = (Product)bf.Deserialize(fs);
fs.Close();

In some next article I'll show you how can we serialize an object using Soap formatter that is also known as XML serialization.

1 comment:

Anandarajeshwaran.J said...

that was great code man.thankyou very much for the code.

www.BeginWithDisbelief.com