Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I provide a deep clone when implementing ICloneable?

Tags:

.net

oop

It is unclear to me from the MSDN documentation if I should provide a deep or a shallow clone when implementing ICloneable. What is the preferred option?

like image 975
Jim Burger Avatar asked Sep 30 '08 02:09

Jim Burger


People also ask

Which of the following method should be implemented when ICloneable interface is used?

The ICloneable interface simply requires that your implementation of the Clone() method return a copy of the current object instance.


2 Answers

Short answer: Yes.

Long Answer: Don't use ICloneable. That is because .Clone isn't defined as being a shallow or a deep clone. You should implement your own IClone interface, and describe how the clone should work.

like image 133
MagicKat Avatar answered Sep 28 '22 02:09

MagicKat


Clones are deep by default, thats the naming convention and copy constructors can be shallow if they want, for performance reasons.

Edit: This naming convention goes beyond boundaries, its the same for .Net, Java, C++, Javascript, etc... the actual source is beyond my knowledge but its part of the standard Object Oriented lexicon, just like objects, and classes. Thus MSDN doesn't specify implementation because its a given by the word itself (of course lots of newcomers to OO languages don't know this, and they SHOULD specify it, but then again their documentation is quite frugal anyways)

like image 23
Robert Gould Avatar answered Sep 28 '22 03:09

Robert Gould