C# StringBuilder

Beginner
7 min read
Updated: Nov 2026
3 examples
StringBuilder

Definition and Usage

In C#, StringBuilder is a text buffer you can change. A normal string is immutable, so every + or Replace on it returns a brand-new string. A StringBuilder keeps one growing buffer and edits it in place. You add text with Append(), edit it with Insert(), Remove(), and Replace(), and get the finished string with ToString().

Length is how many characters a builder holds; Capacity is how many fit before it needs more memory (16 by default). Capacity grows on its own, and EnsureCapacity() can reserve room ahead of time. The indexer is writable: sb[0] = 'A' changes one character. Add using System.Text; to use the class. The StringBuilder Methods index lists every guide.

Not always faster.

For a few fixed pieces, "a" + b + "c" or an interpolated string is just as quick. Use StringBuilder when text is built in many steps, such as in a loop. It is not thread-safe.

C# Syntax

Common first steps:

C#
using System.Text;

StringBuilder sb = new StringBuilder();         // empty, capacity 16
StringBuilder roomy = new StringBuilder(256);   // empty, room for 256 chars

sb.Append("Total: ").Append(42);                // "Total: 42"
int chars = sb.Length;                          // 9
string text = sb.ToString();                    // the finished string

StringBuilder vs string

Pick the type that matches how the text is made:

Type / toolCan it change?Good for
stringNo. Every edit returns a new stringFixed text, keys, comparisons, a few joined pieces
StringBuilderYes. Edits happen in one bufferText built in many steps or inside loops
string.Concat, Join, FormatNo. Makes one new stringCombining pieces you already have, or one formatted message

What Each Method Returns

Methods that return the same builder can be chained, as in sb.Append("a").Insert(0, "b"). The others give you a value:

MethodsReturnChain?
Append, AppendFormat, AppendJoin, AppendLine, Insert, Remove, Replace, ClearThe same StringBuilderYes
ToString, Equals, EnsureCapacitystring, bool, intNo
CopyTo, GetChunksvoid, a chunk enumeratorNo

C# Examples

Example 1 — Append, Insert, and ToString

Build a short message in a few steps, fix its front, and turn the buffer into a string.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder();

        sb.Append("learn");
        sb.Append(' ').Append("C#");
        Console.WriteLine(sb.ToString());

        sb.Insert(0, "Let's ");
        sb.Append('!');
        string message = sb.ToString();

        Console.WriteLine(message);
        Console.WriteLine(message.Length);
    }
}

How It Works

  1. An empty buffer. new StringBuilder() starts with no text. It needs using System.Text;, because that is the namespace the class lives in.
  2. Grow it at the end. Append("learn") adds a word, and the chained Append(' ').Append("C#") adds a space and another word to the very same builder.
  3. Edit the front. Insert(0, "Let's ") pushes the existing text to the right and puts the new words at position 0. No new string object is created for this step.
  4. Finish with ToString. ToString() copies the buffer into a real string. The message has 15 characters: 6 for Let's, 8 for learn C#, and 1 for the !.

Example 2 — Build Text in a Loop: string + vs StringBuilder

Both loops produce the same text, but only the string loop creates a new string on every pass.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        string slow = "";
        for (int i = 0; i < 5; i++) {
            slow += i + ",";
        }

        StringBuilder fast = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            fast.Append(i).Append(',');
        }

        Console.WriteLine(slow);
        Console.WriteLine(fast.ToString());
        Console.WriteLine(slow == fast.ToString());
    }
}

How It Works

  1. Strings never change. slow += ... cannot edit the old string. It builds a new string that holds the old text plus the new part, and the old one becomes garbage.
  2. The builder grows in place. fast.Append(i).Append(',') writes the number and the comma into the same buffer. The buffer only gets more memory now and then, when it is full.
  3. Same result. Both lines print 0,1,2,3,4,, and == on the two strings is True, because string equality compares the characters.
  4. Why it matters. Five passes are cheap either way. With thousands, the += loop copies more and more text each time, while the builder stays fast.

Example 3 — Length, Capacity, and the Indexer

Watch the character count and the room, then change one character with the indexer.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder(8);
        Console.WriteLine(sb.Length + " / " + sb.Capacity);

        sb.Append("abcd");
        Console.WriteLine(sb.Length + " / " + sb.Capacity);

        sb.Append("efghij");
        Console.WriteLine(sb.Length);
        Console.WriteLine(sb.Capacity >= sb.Length);

        sb[0] = 'A';
        Console.WriteLine(sb.ToString());
    }
}

How It Works

  1. Pick a starting room. new StringBuilder(8) holds no text yet but has room for 8 characters, so the first line is 0 / 8.
  2. Length counts text. After four letters, Length is 4 while Capacity is still 8. Nothing had to grow.
  3. Room grows by itself. Six more letters make 10, more than 8, so the builder takes extra memory. The exact new capacity is an internal detail, which is why only Capacity >= Length is printed.
  4. Change one character. Unlike a string, a builder has a writable indexer. sb[0] = 'A' swaps the first letter in place, and the text becomes Abcdefghij.

Next: C# StringBuilder Methods Index

Start withWhy
Append()Add any value to the end of the builder and get the same builder back for chaining.
AppendLine()Add optional text followed by a line break (Environment.NewLine).
Insert()Put text or a value at any position; the characters after it move to the right.
ToString()Turn the builder (or part of it) into a normal string you can print, store, or compare.

Full list: C# StringBuilder Methods index (/c-sharp/string-builder/method). Related collections: C# List.

Frequently Asked Questions

It is a class in System.Text that holds text you can change. You add text with Append, change it with Insert, Remove, and Replace, and get the finished string with ToString. A normal string cannot change after it is created.
When you build text in many steps, especially in a loop. Each + on a string makes a new string, while a StringBuilder grows one buffer. For a few fixed pieces, + is just as fast.
Length is how many characters the builder holds now. Capacity is how many fit before it needs more memory; it starts at 16 and grows on its own.
Append, Insert, Remove, Replace, Clear, and the other Append methods return the same StringBuilder, so sb.Append("a").Insert(0, "b") works in one statement.
No. Give each thread its own builder, or protect a shared one with a lock.

Browse every StringBuilder method

Open the methods index for categorized guides with examples and FAQs.

StringBuilder Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful