Friday, May 11, 2007

Deep Serialization using MemoryStream

I found this quite easy to use MemoryStream and BinaryFormatter object to provide deep copy functionality.

For full article, please visit : http://www.c-sharpcorner.com/UploadFile/sd_surajit/cloning05032007012620AM/cloning.aspx

Following is the code snippet for quick look:

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;



public
Class Test : IClonable

{

public Test()

{

}

// deep copy in separeate memory space

public
object Clone()

{

MemoryStream ms = new MemoryStream();

BinaryFormatter bf = new BinaryFormatter();

bf.Serialize(ms, this);

ms.Position = 0;

object obj = bf.Deserialize(ms);

ms.Close();

return obj;

}

}

No comments: