ICloneable
suggest changeSyntax
- object ICloneable.Clone() { return Clone(); } // Explicit implementation. It is not a private method; callers reach it through ICloneable. It can forward to a public Clone method.
- public Foo Clone() { return new Foo(this); } // Public clone method should utilize the copy constructor logic.
Remarks
ICloneable.Clone returns object, so the result is not type-safe. It is common to also offer a public method that returns the concrete type.
The author decides whether the clone is shallow or deep. A shallow copy is enough when the referenced objects are immutable, because the clone cannot observe a later change. A deep copy matters when the clone must not share mutable objects.
An interface method can be implemented explicitly, as the first syntax line shows. That method is not private. Code that has an ICloneable reference can still call it.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents