Choosing StringBuilder
Question
When would you use a
StringBuilder?
Short interview answer
Use
StringBuilderwhen performing many string modifications, especially in loops or when the final size is unknown. It avoids creating a new string for every intermediate change.
Detailed answer
For a few concatenations, ordinary string interpolation is usually clearer. When building a large report line by line, each + operation would create another immutable string:
var builder = new StringBuilder();
foreach (var row in rows)
builder.AppendLine($"{row.Id}: {row.Name}");
var report = builder.ToString();
StringBuilder maintains a mutable buffer and creates the final string when ToString() is called.