DRYing out implementation of ICloneable in several classes

Posted by Sarah Vessels on Stack Overflow See other posts from Stack Overflow or by Sarah Vessels
Published on 2010-05-26T17:22:40Z Indexed on 2010/05/26 17:31 UTC
Read the original article Hit count: 271

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about clone