Strings:
The class System.String enables us to handle strings in C#.The class System.String enables us to handle strings in C#.
Strings are Immutable
The string class has an important feature – the character sequences stored in a variable of the class are never changing (immutable). After being assigned once, the content of the variable does not change directly – if we try to change the value, it will be saved to a new location in the dynamic memory and the variable will point to it.
When we initialize a variable of type string with a string literal, the memory checks invisibly for us whether this value already exists. If the value already exists, the new variable is simply pointed to it. If not, a new block of memory is allocated, the value is stored in it and the reference is changed to point to the new block. The string interning in .NET is possible because strings are immutable by design and it is not likely that the memory block referenced by several string variables will simultaneously be changed by someone.
StringBuilder
StringBuilder are mutable.
The StringBuilder class is an implementation of a string in C#, but different than the class String. Unlike the already familiar for us strings, the objects of the StringBuilder class are not immutable, namely edit operations do not require creating a new object in the memory. This reduces the unnecessary transfer of data in memory when performing basic operations such as string concatenation.
StringBuilder keeps a buffer with a certain capacity (16 characters by default). The buffer is implemented as an array of characters that is provided to the developer by a user-friendly interface – methods that quickly and easily add and edit elements of the string. At any moment part of the characters in the buffer are used and the rest stay in reserve. This allows the addition to work very quickly. Other operations also operate faster than the class string, because the changes do not create a new object.