0

I was recently asked this question : What is the difference between String and StringBuilders ?

I knew I had read somewhere that StringBuilders are immutable, but what immutable was and how do operations on StringBuilder turn out to be faster than String, that I was unaware of.

Please can anyone help me understand this ?

Yasser Shaikh
  • 44,064
  • 44
  • 190
  • 271
  • 4
    Oh no, StringBuilders are not immutable.... Strings are. Immutable means the internal state of the object cannot be changed. You cannot change a particular character inside of a string (or add or delete characters). But you change the state of string builders all the time (e.g. with Append). – Ray Toal Jun 20 '12 at 06:16
  • possible duplicate of [string is immutable and stringbuilder is mutable](http://stackoverflow.com/questions/665499/string-is-immutable-and-stringbuilder-is-mutable) – nawfal Jul 16 '14 at 20:09

2 Answers2

6

No, String is immutable - whereas StringBuilder is mutable. That's the whole point of it. You use it to build a string, usually from lots of append operations. You can do this without creating a fresh copy of all the data each time, which is what would happen if you use String:

// Bad
string x = "";
for (int i = 0; i < 100; i++)
{
    x += i;
}

// Good
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++)
{
    builder.Append(i);
}
string x = builder.ToString();

See my article on string concatenation and my other article on strings in general for more details.

In general, an immutable data type is one where you can't change the data in an object after creation, whereas a mutable one lets you change (mutate, hence the name) it. It's not quite as simple as it sounds though - see Eric Lippert's blog post on kinds of immutability for more information.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • "String is immutable " "You can do this without creating a fresh copy of all the data each time, which is what would happen if you use String" is that means string is better than stringbuilder since in string concat op not creating fresh copy? – user786 Jun 14 '16 at 15:59
  • @Alex: No, string concatenation *does* create a new copy each time. – Jon Skeet Jun 14 '16 at 16:09
1

For string : every time a operation is performed on the string to change it ,it leads to a new instance.

For Further explanation please refer below link:

Difference between string and StringBuilder in c#

Community
  • 1
  • 1
Gupta Vini
  • 430
  • 4
  • 5