Skip to content

String Immutability

Question

Can a string be modified?

Short interview answer

No. A string is immutable: an operation that appears to change it creates a new string value instead.

Detailed answer

string is a reference type, but its contents cannot be changed after construction:

var name = "Ada";
name += " Lovelace"; // A new string is created; "Ada" was not modified.

This makes strings safe to share, but repeated concatenation in a loop can create unnecessary allocations.

Sources