« Home | MS Certifications » | Exception Handling » | Coding Slave » | VS2005 & SQL Server 2005 » | AvPad » | Visual Studio 2005 Pricing » | Resharper » | VB6 Revolt » | SQL Server Broker (SSB) » | VB MVP Revolt »

Cloning made easy

Cloning an object is simple if you use serialization.

[Serializable]
public class Sheep : ICloneable
{
private string _name;

public Sheep()
{
}

public string Name
{
get { return _name; }
set { _name = value; }
}

public object Clone()
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, this);
ms.Position = 0;
return formatter.Deserialize(ms);
}
}

This is an AWESoME tip! I never thought of it. Pretty lightweight, too, with the binary formatter.

This is really clever - I like it a lot. It would have come in handy a while back, and I'm sure it will again in the future. But I think I might change it like:

public object Clone()
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
using (MemoryStream ms = new MemoryStream())
{
formatter.Serialize(ms, this);
ms.Position = 0;
}
return formatter.Deserialize(ms);
}

By the way, thanks for posting your ReSharper shortcut configuration - it saved me some time trying to figure out a few...

Cheers.

Post a Comment