What is the difference between a mutable and immutable string in C#?
Mutable and immutable are English words meaning "can change" and "cannot change" respectively. The meaning of the words is the same in the IT context; i.e.
- a mutable string can be changed, and
- an immutable string cannot be changed.
The meanings of these words are the same in C# / .NET as in other programming languages / environments, though (obviously) the names of the types may differ, as may other details.
For the record:
-
String
is the standard C# / .Net immutable string type -
StringBuilder
is the standard C# / .Net mutable string type
To "effect a change" on a string represented as a C# String
, you actually create a new String
object. The original String
is not changed ... because it is unchangeable.
In most cases it is better to use String
because it is easier reason about them; e.g. you don't need to consider the possibility that some other thread might "change my string".
However, when you need to construct or modify a string using a sequence of operations, it may be more efficient to use a StringBuilder
. An example is when you are concatenating many string fragments to form a large string:
- If you do this as a sequence of
String
concatenations, you copyO(N^2)
characters, whereN
is the number of component strings. - If use a
StringBuilder
you only copyO(N)
characters.
And finally, for those people who assert that a StringBuilder
is not a string because it is not immutable, the Microsoft documentation describes StringBuilder
thus:
"Represents a mutable string of characters. This class cannot be inherited."
String
is immutable
i.e. strings cannot be altered. When you alter a string (by adding to it for example), you are actually creating a new string.
But StringBuilder
is not immutable (rather, it is mutable)
so if you have to alter a string many times, such as multiple concatenations, then use StringBuilder
.