OOP & concepts

string vs StringBuilder in C#: when to use which

OOP & concepts · · Published 2026-08-08

A string never changes once created; every "modification" produces a new string. A StringBuilder keeps a growable buffer and modifies it in place. The rule of thumb: use StringBuilder when you build text in a loop, and plain strings almost everywhere else.

Immutability in practice

string s = "Hello";
string t = s.ToUpper();   // s is still "Hello"; t is a new string "HELLO"
s += " world";            // creates a third string and points s at it

Immutability makes strings safe to share between threads and to use as dictionary keys. The cost appears in loops:

// Quadratic: each += copies everything built so far
string csv = "";
foreach (var row in rows) csv += row.Id + "," + row.Name + "\n";

// Linear: appends into one buffer
var sb = new StringBuilder();
foreach (var row in rows) sb.Append(row.Id).Append(',').Append(row.Name).Append('\n');
string csv2 = sb.ToString();

With 10,000 rows, the first version copies the growing text 10,000 times; the second copies each piece about once (the buffer occasionally doubles in size). The difference grows with the number of iterations.

When plain strings are fine

Comparison

stringStringBuilder
MutableNoYes
Thread-safe for readingYesNo (instances are not thread-safe)
Best forValues, keys, a few concatenationsBuilding text in loops, many appends
EqualityCompares text (== overloaded)Reference; compare ToString() results
NamespaceSystemSystem.Text

StringBuilder tips

In ASP.NET pages

Building an HTML fragment or a CSV export row by row is the typical use, as in Send a GridView by e-mail and Export a file list to CSV. Whatever builds the text, encode user data (HttpUtility.HtmlEncode) before appending it to HTML. And for SQL, never build statements by appending values: use parameters (SQL injection).

The alias question, string or String, is covered in string vs String.

Official documentation