Difference between String and StringBuilder

Strings are Immutable means whenever you change any value of string variable, a new object is created in memory. That’s why where a significant number of strings modifications need to be done, StringBuilder should be used. Its present in System.TextBuilder namespace.

Now questions comes, why strings are Immutable or what are the benefits of immutability :

  • First, All Immutable instances are thread safe. Because on modifying their values, a new instance is created , So no Thread can actually modify it.
  • There will be no side-effect on passing an immutable types as parameter in a function, as if there is x = “abc” in the starting of function,  that doesn’t change in the body of the method, then x == "abc" at the end of the method.
  • Copying is fast and simple, to create a clone just return this. Since the copy can’t be changed anyway, pretending something is its own copy is safe.
  • You can use strings in Hash-table, key-value pairs collection for their key part.