Tuesday 24 February 2009

Shallow Copy vs Deep Copy in .NET

Shallow Copy:

// Creates a shallow copy
public object Clone()
{
return this.MemberwiseClone();
}

Deep Copy:

// Creates a deep copy
public object DeepCopy()
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);

object copy = formatter.Deserialize(stream);
stream.Close();

return copy;
}

http://www.codeproject.com/KB/cs/ShallowVsDeepCopy.aspx


No comments: