Surprisingly, String.Clone() doesn't return a copy of a string as String.Copy() would do. Instead, it returns 'this', the original string.
I would like to understand why the .Net Framework team choose to go this way.
As per MSDN:
The ICloneable interface [...] requires that your implementation of the Clone method return a copy of the current object instance.
String.Clone() clearly doesn't follow this guideline.
I know that strings are immutable, but if immutability was the reason here, String.Copy() would also return this but it doesn't.
This is a rather theoretical question, of course.
How could you detect the difference? Only by comparing the two references using
object.ReferenceEquals. But by any semantic operation on the string you can't tell the difference.Comparing strings by reference is almost always a bug to begin with because you can rarely rely on interning to happen or not happen.
This issue does not only apply to
String. If you had an immutablePointclass, why would you return a fresh object fromClone? No need.IClonableis rarely used and rarely useful, anyway. If you want to expose users of your class a way to obtain a copy of a given instance you don't need to inherit fromIClonableat all.