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.
Posted by Suman Chakrabarti | 3:08 PM
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.
Posted by Anonymous | 5:22 PM