Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does String.Clone() returns the original string and not a copy of it?

Tags:

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.

like image 965
Sylvain Rodrigue Avatar asked Dec 18 '13 20:12

Sylvain Rodrigue


People also ask

How do you clone a string?

Strings in C# can be cloned, and you can use the Clone() method for this purpose. It is a method of the String class. When used on a string, it returns the copy of the string. The returned value is a reference of that exact string or string data.

What is clone in C# with example?

In C#, Clone() is a String method. It is used to clone the string object, which returns another copy of that data. In other words, it returns a reference to this instance of String. The return value will be only another view of the same data. Clone method called directly on current String instance.


2 Answers

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 immutable Point class, why would you return a fresh object from Clone? No need.

IClonable is 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 from IClonable at all.

like image 195
usr Avatar answered Oct 10 '22 22:10

usr


IClonable is somewhat deprecated as it's unclear what "Clone" means from a system-wide standpoint (deep, shallow...). See http://blogs.msdn.com/b/brada/archive/2003/04/09/49935.aspx

The reference source documents the Clone method with the following comment:

// There's no point in cloning a string since they're immutable, so we simply return this.

Interning of strings means that it's hard to collect strings (they can be referenced more than once) which means really making a new copy of string serves only to stress the system. Plus, interning and copying conflict with each other--so the general rule of interning wins.

like image 37
Peter Ritchie Avatar answered Oct 10 '22 22:10

Peter Ritchie