what's the use of string.Clone()?

Arseny picture Arseny · Aug 12, 2010 · Viewed 16.6k times · Source

there are 2 examples of code: # 1

 string str1 = "hello";
 string str2 = str1; //reference to the same string
 str1 = "bye"; //new string created

and # 2

string str3 = "hello";
string str4 = (string)str3.Clone();//reference to the same string
str3 = "bye";//new string created

looks like they are identical aren't they? so what is the benefit to use Clone()? can you give me an example when I cannot use code#1 but code#2 ?

Answer

Elisha picture Elisha · Aug 12, 2010

This is useful since string implements ICloneable, so you can create a copy of clones for a collection of ICloneable items. This is boring when the collection is of strings only, but it's useful when the collection contains multiple types that implement ICloneable.

As for copying a single string it has no use, since it returns by design a reference to itself.