Back to Home

How to use StringBuilder in C#

StringBuilder in C# is a mutable string class that efficiently handles string modifications. Unlike regular strings which are immutable, StringBuilder modifies the same object, avoiding memory allocations for each change.

Use StringBuilder when concatenating strings in loops or making many modifications. For simple concatenations, regular string operations or interpolation are more readable and often sufficient.

StringBuilder provides methods like Append(), AppendLine(), Insert(), Remove(), and Replace() for efficient string manipulation.

C# Example Code
using System;
using System.Text;

// Basic StringBuilder usage
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
Console.WriteLine(sb.ToString());  // Hello World

// AppendLine for new lines
StringBuilder message = new StringBuilder();
message.AppendLine("Line 1");
message.AppendLine("Line 2");
message.AppendLine("Line 3");
Console.WriteLine(message.ToString());

// Method chaining
StringBuilder chain = new StringBuilder()
    .Append("First")
    .Append(" ")
    .Append("Second")
    .Append(" ")
    .Append("Third");
Console.WriteLine(chain.ToString());

// Building strings in loops (efficient)
StringBuilder loop = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
    loop.Append($"Number {i}, ");
}
Console.WriteLine(loop.ToString().TrimEnd(',', ' '));

// Insert and Remove
StringBuilder edit = new StringBuilder("Hello World");
edit.Insert(6, "Beautiful ");  // Insert at position
Console.WriteLine(edit);  // Hello Beautiful World

edit.Remove(6, 10);  // Remove 10 chars from position 6
Console.WriteLine(edit);  // Hello World

// Replace
StringBuilder replace = new StringBuilder("The cat and the cat");
replace.Replace("cat", "dog");
Console.WriteLine(replace);  // The dog and the dog

// Initial capacity for performance
StringBuilder capacity = new StringBuilder(1000);  // Pre-allocate space
for (int i = 0; i < 100; i++)
{
    capacity.Append($"Item {i}, ");
}
Console.WriteLine($"Built {capacity.Length} characters");

When to Use StringBuilder

Use StringBuilder when concatenating in a loop or performing many modifications (typically 5+). For a handful of fixed parts, $"" interpolation is cleaner and fast enough.

C# Example Code
// Fine — small number of fixed parts, no loop
string greeting = $"Hello, {firstName} {lastName}!";

// Slow — each += allocates a brand-new string and discards the old one
string csv = "";
foreach (var item in items)
    csv += item + ","; // n intermediate strings for n items

// Fast — StringBuilder mutates one internal buffer
var sb = new StringBuilder();
foreach (var item in items)
    sb.Append(item).Append(',');
string result = sb.ToString();

AppendFormat

AppendFormat works like string.Format but writes directly into the builder, avoiding an intermediate string allocation.

C# Example Code
var sb = new StringBuilder();
sb.AppendFormat("Name: {0}", "Alice");
sb.AppendFormat(", Age: {0}", 30);
sb.AppendFormat(", Score: {0:F2}", 98.765);
Console.WriteLine(sb.ToString()); // Name: Alice, Age: 30, Score: 98.77

// Building a CSV report
var report = new StringBuilder();
report.AppendLine("Id,Name,Score");

var data = new[] { (1, "Alice", 95.5), (2, "Bob", 87.2) };
foreach (var (id, name, score) in data)
    report.AppendFormat("{0},{1},{2:F1}\n", id, name, score);

Console.WriteLine(report.ToString());
// Id,Name,Score
// 1,Alice,95.5
// 2,Bob,87.2

When NOT to Use StringBuilder

C# Example Code
// Overkill for a few fixed parts — just use interpolation
var sb = new StringBuilder(); // unnecessary
sb.Append("Hello, ");
sb.Append(name);
sb.Append("!");
string msg = sb.ToString();
// Better:
string msg2 = $"Hello, {name}!";

// Don't use StringBuilder to join a plain collection — String.Join is cleaner
var parts = new[] { "one", "two", "three" };
var sbJoin = new StringBuilder();
for (int i = 0; i < parts.Length; i++)
{
    sbJoin.Append(parts[i]);
    if (i < parts.Length - 1) sbJoin.Append(", ");
}
// Better:
string joined = string.Join(", ", parts); // "one, two, three"

String.Join vs StringBuilder

ApproachBest for
string.Join(sep, collection)Joining a collection with a separator
StringBuilderLoops with complex per-item logic
string.Concat(a, b, c)Joining without a separator, no loop
$"" interpolationSmall fixed-structure strings
C# Example Code
var words = new List<string> { "apple", "banana", "cherry" };

// String.Join — cleanest for collections
string joined  = string.Join(", ", words);        // apple, banana, cherry
string csv     = string.Join(",", words);          // apple,banana,cherry
string lines   = string.Join(Environment.NewLine, words);

// StringBuilder — best when per-item logic is complex
var sb = new StringBuilder();
foreach (var word in words)
{
    sb.Append(word.ToUpper());
    sb.Append(" | ");
}
if (sb.Length > 0) sb.Length -= 3; // trim trailing " | "
Console.WriteLine(sb.ToString()); // APPLE | BANANA | CHERRY

Take It Further

The C# Player's Guide book cover

The community's favorite C# guide — teaches every concept you just read about with clarity.

The C# Player's Guide — 5th Edition · RB Whitaker

Get it on Amazon →

As an Amazon Associate I earn from qualifying purchases.