Monday, July 21, 2008

Serializing and deserializing objects

To serialize an object, you simply create an instance of  BinaryFormatter which is part of System.Runtime.Serialization.Formatters.Binary namespace and use Serialize or Deserialize methods.

The following example shows how an object can be serialized and deserialized. I used memory stream for my example; you can also use other kinds of stream such as FileStream. SerializingObject is the object that's being serialized. I serialize it then deserialize it to its original type which is DataTable.

Here is the example:

using(MemoryStream = new MemoryStream())
{

DataTable SerializingObject =new DataTable();

BinaryFormatter MyBinaryFormatter = new BinaryFormatter();
MyBinaryFormatter .Serialize(MyMemoryStream , SerializingObject);
MyMemoryStream .Position = 0;
DataTable DeserializingObject= (DataTable)MyBinaryFormatter.Deserialize(TableMemoryStream)

}

No comments: