Immutability of strings
suggest changeStrings are immutable. You cannot change an existing string. Any operation that looks like a change creates a new string. Replacing one character of a very long string still allocates a new string.
string veryLongString = ...
// memory is allocated
string newString = veryLongString.Remove(0,1); // removes first character of the string.
If you need to perform many operations on a string, use StringBuilder, which is designed for efficient string manipulation:
var sb = new StringBuilder(someInitialString);
foreach(var str in manyManyStrings)
{
sb.Append(str);
}
var finalString = sb.ToString();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents