1

Occasionally I've found that string implements IClonable interface and I wondered why, since string is immutable. Further I tried to guess how it should work and what to expect from cloning a string... I expected it should return same string reference when string interning is enabled, and create new object in case it is disabled (I undertand that in that case equality operator wouldn't have worked correctly anymore - probably that's why it isn't implemented this way).

When I decompiled the method from .NET sources - I found that the implementation is just returning self-reference (this pointer) without any extra logic. And there is a comment on it:

// Method required for the ICloneable interface.
// There's no point in cloning a string since they're immutable, so we simply return this.

So .NET team themselves say there is no point calling this method. But why did they implement it at all then?

Sasha
  • 8,537
  • 4
  • 49
  • 76
  • 2
    http://stackoverflow.com/questions/3465377/whats-the-use-of-string-clone see this post – nsgocev Aug 04 '14 at 14:46
  • Note the [documentation for `ICloneable.Clone()`](http://msdn.microsoft.com/en-us/library/system.icloneable.clone.aspx) says (emphasis mine): *An implementation of `Clone` can perform either a deep copy or a shallow copy. In a deep copy, all objects are duplicated; in a shallow copy, only the top-level objects are duplicated and the lower levels contain references. Because callers of `Clone` cannot depend on the method performing a predictable cloning operation,* ***we recommend that `ICloneable` not be implemented in public APIs.*** So there. – Frédéric Hamidi Aug 04 '14 at 14:48
  • @FrédéricHamidi: but that would be a reason against, wouldn't it? – Tim Schmelter Aug 04 '14 at 14:51
  • @Tim, yes, absolutely. Having `string`, which is as public an API as they get, implement `ICloneable` may very well have been a mistake, at least in retrospect. – Frédéric Hamidi Aug 04 '14 at 14:52
  • @nsgocev, answer in that post provides the theoretical usage. I can create collection of IClonables and clone it. But practically that's useless - what else can I do with a collection of IClonables? How to use the copied object through this abstraction which has only one method? I don't see practical usage of this solution. – Sasha Aug 04 '14 at 14:58

0 Answers0