Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Strings and Text

The StringBuilder class

Reference for System.Text.StringBuilder: efficient string building with Append, AppendLine, Insert, Remove, Replace, capacity, and when not to use it.

StringBuilder (namespace System.Text) is a mutable buffer of characters. You append, insert, remove and replace text in it, and when you are done you call ToString() once to get a regular string. It exists because string is immutable: every += on a string copies all the characters so far, which makes long loops quadratic.

A StringBuilder keeps its text in a chain of chunks and grows as needed, so appending is cheap. It is not thread-safe, and for a handful of concatenations a plain +, interpolation or string.Join is simpler and just as fast.

C#
using System.Text;

var sb = new StringBuilder();
sb.Append("Hello").Append(", ").Append("World");
string text = sb.ToString();

Try it

C# Appending and formatting

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.

C# Editing, indexing and capacity

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

C#
public StringBuilder()
public StringBuilder(int capacity)
public StringBuilder(string? value)
public StringBuilder(string? value, int capacity)
public StringBuilder(int capacity, int maxCapacity)

public StringBuilder Append(...)          // string, char, char repeated, numbers, bool, object, spans, interpolated handler
public StringBuilder AppendLine()
public StringBuilder AppendLine(string? value)
public StringBuilder AppendFormat(string format, params object?[] args)
public StringBuilder AppendJoin(string? separator, IEnumerable<T> values)
public StringBuilder Insert(int index, ...)
public StringBuilder Remove(int startIndex, int length)
public StringBuilder Replace(string oldValue, string? newValue)
public StringBuilder Clear()
public override string ToString()
public string ToString(int startIndex, int length)
Member Description
Length Current number of chars; can be set to truncate or pad with '\0'.
Capacity Size of the current buffer before it must grow.
MaxCapacity Upper limit for Capacity; default is int.MaxValue.
this[int] Gets or sets a single character.
Chunks, GetChunks() Enumerate the internal pieces without building one big string.

Returns: most methods return the same builder, so calls chain. ToString() allocates a new string each time.

Errors / undefined behavior: ArgumentOutOfRangeException for an invalid index, a negative length, or growth beyond MaxCapacity. IndexOutOfRangeException for the indexer.

Usage notes

  • When it pays off. Use a builder when you append in a loop of unknown size, or build text in many steps. For a fixed number of pieces, string.Concat, string.Join or interpolation is better.
  • Set a starting capacity if you know the rough size; it avoids repeated growth.
  • Append numbers directly. sb.Append(42) avoids creating a temporary string. In recent .NET versions sb.Append($"...") with interpolation writes straight into the builder without an intermediate string.
  • ToString() is a copy. Calling it in a loop negates the benefit. Call it once at the end, or use GetChunks() to stream the pieces.
  • Indexer cost. sb[i] is cheap for small builders but can be slow on large, multi-chunk ones; use ToString() or chunks for heavy random access.
  • Not thread-safe. Do not share one instance between threads without locking.
  • Replace and Remove operate on the buffer, so they avoid copying the whole text each time, unlike their string counterparts.
  • Pooling. Hot paths can reuse builders with ObjectPool<StringBuilder> or use string.Create and ValueStringBuilder-style helpers.
  • New lines. AppendLine uses the environment's newline (\n on Linux, \r\n on Windows).