Roadmap › C# Language — Basics to Advanced › Module: Getting Started
Lessons in this course (38)
7. Strings, StringBuilder and immutability
Basic★ Must knowLesson 7 of 38
string is a reference type that behaves like a value: it is immutable — every "change" creates a new string.
csharp
string s = "a";
s += "b"; // allocates a new string "ab"; "a" becomes garbage
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.Append(i).Append(',');
string csv = sb.ToString(); // one final allocation- Use
StringBuilderwhen concatenating in loops; for a few concatenations+or interpolation is fine. - String interning: identical literals share one instance (
string.Intern). - Compare with
string.Equals(a, b, StringComparison.OrdinalIgnoreCase)rather thanToLower(). string.IsNullOrWhiteSpace(x)coversnull,""and" ".