Posted By: bonk | Jun 22nd, 2006 @ 11:23 PM
page 1 of 1
Comments: 5 | Views: 9180
bonk
bonk
Ich bin der Wurstfachverkäuferin !
I have come across the need to distinguish between the creation of a
deep and a shallow copy and with great interest I have read this
article:

http://blogs.msdn.com/brada/archive/2004/05/03/125427.aspx

This article seems to hint that I should not use System.IClonable but
instead define my own interface(s) for cloning. Now since this article
is rather old and since they did not obsolete IClonable there might be
a new "best practise".

How do I implement Cloning of objects correctly if I want to explicitly
distinguish between deep and shallow copies? Should I

a) use System.IClonable for deep copies and override
object.MemberwiseClone for shallow copies ?

b) define my own IClonable, for example like this:
    interface IClonable <T>
    {
        /// <summary>
        /// creates a deep or shallow copy of the current object
        /// </summary>
        /// <param name="deep">
        /// if <c>true</c> a deep copy should be returned,
        /// wich means that the copied object and all
        /// objects referenced by the object are copied recursively
        /// if <c>false</c>a shallow copy should be retruned,
        /// wich means that  only the top level references
        /// are copied
        ///</param>
        /// <returns>a deep or a shallow copy of the current
object</returns>
        T Clone (bool deep);
    }

c) do something else I did not think of yet ?

Dr Herbie
Dr Herbie
Horses for courses
I tend to reserve ICloneable for shallow copies and define my own IDeepCopy interface. This is because I got the impression that ICloneable was intended for shallow copies (can't remember where or when I got this idea, I think if was a webcast somewhere).


It doesn't really matter which way you do things, as long as you remain consistent and document the decision so that anyone else using your code will understand.

Herbie

Tensor
Tensor
Im in yr house upgrading yr family
I would always use ICloneable for a deep copy - ie serialize the current object and spit it back out. If I wanted a shallow copy I would probably do my own interface or some such.


Agree that as long as you are consistent you are on the right path - its just that I think you should also be consisten wit hthe docuimentation. The docs on system.memberwiseclone are fairly explicit on this subject.
Dr Herbie
Dr Herbie
Horses for courses
Hmmm.  Thanks for the links. 
I think that for future projects  I'll use ICloneable for deep and create an IShallowCopy interface.


Frank Hileman
Frank Hileman
VG.net
Usually a class should support only deep or shallow cloning, not both. The design determines which is appropriate. Only generic data structures used in a variety of situations (linked list, array lists) need to support both deep and shallow.
page 1 of 1
Comments: 5 | Views: 9180
Microsoft Communities