Wednesday, July 02, 2008

Cloning using Serialization

I found some great C# code the other day which allows deep copying of objects, rather than shallow copies which object.Clone() does. Saved heaps of time mucking around with the ICloneable interface, and basically rewriting heaps of code.

You need to decorate the class(es) that you want to clone with the [Serializable] attribute. If you are trying to clone a object of a type which has members of some other class, those classes need to be serializable too.

public static object Clone(object obj)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
return bf.Deserialize(ms);
}

Labels: , ,

0 Comments:

Post a Comment

<< Home