DRYing out implementation of ICloneable in several classes
- by Sarah Vessels
I have several different classes that I want to be cloneable: GenericRow, GenericRows, ParticularRow, and ParticularRows. There is the following class hierarchy: GenericRow is the parent of ParticularRow, and GenericRows is the parent of ParticularRows. Each class implements ICloneable because I want to be able to create deep copies of instances of each. I find myself writing the exact same code for Clone() in each class:
object ICloneable.Clone()
{
object clone;
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
// Serialize this object
formatter.Serialize(stream, this);
stream.Position = 0;
// Deserialize to another object
clone = formatter.Deserialize(stream);
}
return clone;
}
I then provide a convenience wrapper method, for example in GenericRows:
public GenericRows Clone()
{
return (GenericRows)((ICloneable)this).Clone();
}
I am fine with the convenience wrapper methods looking about the same in each class because it's very little code and it does differ from class to class by return type, cast, etc. However, ICloneable.Clone() is identical in all four classes. Can I abstract this somehow so it is only defined in one place? My concern was that if I made some utility class/object extension method, it would not correctly make a deep copy of the particular instance I want copied. Is this a good idea anyway?