Monday, January 18, 2010

Deep copy an object in C#d

A common utility code to DeepClone a given object.
The constraint is that class must implement SerializableAttribute.

public static T DeepCopy(T obj) where T:class
{
T result = null;

using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;

result = (T)formatter.Deserialize(ms);
ms.Close();
}

return result;
}

No comments:

Post a Comment