C# Reference ยท Strings and Text
String immutability
Explains why C# strings are immutable: what Replace and ToUpper really do, the cost of += in loops, thread safety, and the tools for mutable text.
A string object never changes after it is created. Every method that looks like a modification, such as Replace, ToUpper, Trim or Insert, returns a new string and leaves the original untouched. Assigning the result back to a variable only makes that variable point to the new object.
This is a deliberate design. Immutable strings can be shared freely between threads and between objects, used safely as dictionary keys, interned, and cached by hash code, all without defensive copies. The price is that repeated "changes" allocate, so you need the right tool when you build or edit large text.
string s = "cat"; string t = s.ToUpper(); Console.WriteLine(s + " " + t); // cat CAT
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
There is no special syntax: immutability is a property of the type. The tools for mutable or one-shot construction are:
new StringBuilder() char[] ToCharArray() new string(char[] value) static string string.Create<TState>(int length, TState state, SpanAction<char, TState> action)
| Tool | When to use it |
|---|---|
StringBuilder |
Many appends, inserts or removals in a loop. |
char[] or Span<char> |
Fixed-size, in-place edits such as reversing or masking. |
string.Create |
Build a string of known length with no intermediate copy. |
string.Concat / string.Join |
Combine a known set of parts in one allocation. |
Errors / undefined behavior: none in normal code. Modifying a string's memory through unsafe pointers or MemoryMarshal is possible but undefined: other references see the change, interned strings and cached hash codes break, and the runtime may crash.
Usage notes
- Ignoring the return value is the classic bug.
name.Trim();on its own line does nothing. Writename = name.Trim();. +=in a loop is quadratic. Each step copies all characters so far. A handful of concatenations is fine (and the compiler turnsa + b + cinto oneConcat); thousands are not. UseStringBuilderorstring.Join.- Methods may return the same object. When there is nothing to change,
Trim,Replace,ToUpperInvariantand similar often return the original instance. Never use reference identity to detect whether something changed. - Safe keys and sharing. A string in a
Dictionarycan never be altered under the dictionary's feet, and handing a string to another thread needs no lock. - Secrets stay in memory. Because you cannot overwrite a string, passwords held in strings linger until garbage collection. Use
char[]orbyte[]and clear it when you need to limit that. - Slicing copies.
Substringallocates. To look at a part without copying, use aReadOnlySpan<char>. readonlyis about the variable, not the object.readonly string smeans the field cannot be reassigned; strings themselves are always immutable.