32

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 ?

Arseny
  • 7,251
  • 4
  • 37
  • 52

3 Answers3

31

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.

Elisha
  • 23,310
  • 6
  • 60
  • 75
  • But why may I need the copy of a collection of IClonable objects? How to use that collection further, other than creating one more copy =) ? It's the same as a collection of "System.Object" - it's an impasse. – Sasha Aug 04 '14 at 15:22
21

Not directly in answer to your question, but in case you are looking to actually clone a string, you can use the static string.Copy() method.

phoenix
  • 7,988
  • 6
  • 39
  • 45
Jonathan
  • 1,487
  • 11
  • 12
  • In no case should you use string.Copy. See remarks: https://learn.microsoft.com/en-us/dotnet/api/system.string.copy?view=net-5.0#remarks `However, we do not recommend its use in any .NET implementation.` – ruslanen Feb 02 '21 at 05:23
3

.Clone() in the above code is the same as the simple assignment. Also, string is immutable, so it will copy on write in both cases.

.Clone() would be a lot more useful in cases, where you are using different types, that implement the same interface (in this case IClonable) as you would not be able to use a simple assignment, but could still cast the object returned by Clone() to ICloneable and assign that reference. For instance iterating through a generic collection with ICloneable elements.

Zaki
  • 1,101
  • 9
  • 7