Surprisingly, String.Clone()
doesn\'t return a copy of a string as String.Copy()
would do. Instead, it returns \'this\'
, the original stri
As has been mentioned, since strings are read-only, Clone() behaves reasonably. You virtually never actually need two separate instances of the string, and by not making a copy, memory is saved. In the very rare case that you actually need a copy (for some reason you want Object.ReferenceEquals
to return false
), you can use String.Copy()
instead.
It may seem pointless to have a method that just returns this
. The reason to have such a method is to implement ICloneable
, and I agree that String
should implement ICloneable
so that generic code like
T Foo(T x, ...) where T:ICloneable {/* code that might clone x*/}
can be compatible with String.
It's a little strange to me that the method is public
, though, since there's no reason to call it directly. It would make sense if it were only accessible through a reference to ICloneable
.