The Wayback Machine - https://web.archive.org/web/20261109154017/https://www.geeksforgeeks.org/c-sharp/stringbuilder-in-c-sharp/

StringBuilder in C#

Last Updated : 15 Oct, 2026

StringBuilder is a mutable sequence of characters provided by the System.Text namespace in C#. Unlike String, its contents can be modified without creating a new string object for every operation. It is commonly used when a string needs to be changed frequently.

  • Provides methods such as Append(), Insert(), Replace(), and Remove() to modify text.
  • Supports dynamic capacity allocation, reducing unnecessary memory allocations during repeated string operations.
  • Improves efficiency in scenarios involving frequent string concatenation, especially inside loops.

Example: Program to demonstrates how to use the Append() method.

C#
using System;
using System.Text;

class Geeks {
    static void Main()
    {
        StringBuilder sb = new StringBuilder("GeeksforGeeks");
        Console.WriteLine("Initial StringBuilder: " + sb);
        sb.Append(" is awesome!");
        Console.WriteLine("After append: " + sb);
    }
}

Output
Initial StringBuilder: GeeksforGeeks
After append: GeeksforGeeks is awesome!

Explanation: The Append() method adds the specified text to the end of the existing character sequence.

Memory Allocation for String vs StringBuilder in C#

Declaration

A StringBuilder object can be declared and initialized using its constructor.

Syntax

StringBuilder sb = new StringBuilder("Initial String");

An empty StringBuilder can also be created:

StringBuilder sb = new StringBuilder();

Hierarchy of StringBuilder

The StringBuilder class belongs to the System.Text namespace and directly inherits from System.Object. It is a sealed class, meaning it cannot be inherited by another class.

In .NET implementations where the interface is exposed, StringBuilder also implements ISerializable, a legacy serialization interface.

string_builder
Hierarchy of StringBuilder

StringBuilder Constructors

The StringBuilder class provides multiple constructors for different use cases.

  • StringBuilder(): Creates an empty builder with a default initial capacity of 16 characters.
  • StringBuilder(int capacity): Creates an empty builder with the specified initial capacity.
  • StringBuilder(string value): Initializes the builder with the specified string.
  • StringBuilder(string value, int capacity): Initializes the builder with a string and a specified capacity.
  • StringBuilder(int capacity, int maxCapacity): Creates an empty builder with the specified initial capacity and maximum capacity.

Example: Program to demonstrates different constructors of StringBuilder.

C#
using System;
using System.Text;
class Geeks {
    static void Main()
    {
        StringBuilder sb1 = new StringBuilder();
        sb1.Append("Hello");
        Console.WriteLine("sb1: " + sb1);
        
        StringBuilder sb2 = new StringBuilder(50);
        sb2.Append("Initial capacity is 50");
        Console.WriteLine("sb2: " + sb2);
        
        StringBuilder sb3 = new StringBuilder("Geeks");
        sb3.Append("ForGeeks");
        Console.WriteLine("sb3: " + sb3);
        
        StringBuilder sb4 = new StringBuilder("C#", 30);
        sb4.Append(" Programming");
        Console.WriteLine("sb4: " + sb4);
    }
}

Output
sb1: Hello
sb2: Initial capacity is 50
sb3: GeeksForGeeks
sb4: C# Programming

Explanation: This program demonstrates how to create StringBuilder objects using different constructors and append additional text to them.

Capacity and Length of StringBuilder

The StringBuilder class uses two important properties to manage character storage:

  • Capacity: Represents the number of characters the currently allocated storage can hold before expansion is needed.
  • Length: Represents the number of characters currently stored in the object.

When the content exceeds its current capacity, StringBuilder can automatically expand its internal storage.

C#
using System;
using System.Text;

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

        sb.Append("GeeksForGeeks");

        Console.WriteLine("Capacity: " + sb.Capacity);
        Console.WriteLine("Length: " + sb.Length);

        sb.Append(" Programming");

        Console.WriteLine("Updated Length: " + sb.Length);
    }
}

Output
Capacity: 20
Length: 13
Updated Length: 25

Explanation: Initially, the StringBuilder has a capacity of 20 characters and stores 13 characters. After appending more text, its length becomes 25, causing its internal capacity to expand automatically.

Commonly Used Methods in StringBuilder

The StringBuilder class provides various methods for modifying and accessing character sequences.

Example: Using commonly used StringBuilder methods.

C#
using System;
using System.Text;

class Geeks {
    static void Main()
    {
        StringBuilder sb
            = new StringBuilder("GeeksForGeeks");

        Console.WriteLine("Initial: " + sb);

        sb.Append(" C#");
        Console.WriteLine("After append: " + sb);

        sb.Insert(13, " Programming");
        Console.WriteLine("After insert: " + sb);

        sb.Replace("C#", "CSharp");
        Console.WriteLine("After replace: " + sb);

        sb.Remove(13, 12);
        Console.WriteLine("After remove: " + sb);

        sb.Append("123");

        char[] chars = sb.ToString().ToCharArray();
        Array.Reverse(chars);
        sb = new StringBuilder(new string(chars));

        Console.WriteLine("After reverse: " + sb);

        Console.WriteLine("Capacity: " + sb.Capacity);
        Console.WriteLine("Length: " + sb.Length);
        Console.WriteLine("Character at index 0: " + sb[0]);

        sb[0] = 'X';
        Console.WriteLine("After character update: " + sb);

        Console.WriteLine("Index of 's': "
                          + sb.ToString().IndexOf('s'));

        string result = sb.ToString();
        Console.WriteLine("Final String: " + result);
    }
}

Output
Initial: GeeksForGeeks
After append: GeeksForGeeks C#
After insert: GeeksForGeeks Programming C#
After replace: GeeksForGeeks Programming CSharp
After remove: GeeksForGeeks CSharp
After reverse: 321pr...

Explanation: This program demonstrates common operations using StringBuilder, including appending, inserting, replacing, removing, reversing, accessing and updating characters, and converting the result to a string.

Important StringBuilder Methods

Method or Property

Description

Example

Append(value)

Appends a value to the end.

sb.Append("Geeks");

AppendLine(value)

Appends a value followed by a newline.

sb.AppendLine("Geeks");

AppendFormat()

Appends formatted content.

sb.AppendFormat("{0:F2}", 50);

Insert(index, value)

Inserts a value at the specified index.

sb.Insert(5, " C#");

Replace(oldValue, newValue)

Replaces occurrences of a value.

sb.Replace("Java", "C#");

Remove(startIndex, length)

Removes characters from a specified range.

sb.Remove(0, 5);

Clear()

Removes all characters.

sb.Clear();

ToString()

Converts the content to a string.

string result = sb.ToString();

EnsureCapacity(capacity)

Ensures that capacity is at least the specified value.

sb.EnsureCapacity(50);

CopyTo()

Copies characters to a character array.

sb.CopyTo(0, chars, 0, 5);

Capacity

Gets or sets the current capacity.

int cap = sb.Capacity;

Length

Gets or sets the number of characters.

int len = sb.Length;

MaxCapacity

Returns the maximum capacity.

int max = sb.MaxCapacity;

Chars[index]

Gets or sets the character at the specified index.

sb[0] = 'G';

Note: Unlike Java's StringBuilder, C# does not provide the same Reverse(), CharAt(), SetCharAt(), or Substring() instance methods. In C#, use ToString() with standard string methods when needed, and use the indexer (sb[index]) to access or update a character. To reverse a StringBuilder, use an appropriate approach such as converting it to a character array and reversing that array.

Advantages of StringBuilder

  • Efficient string modification: It avoids creating a new string for every individual change.
  • Dynamic capacity: It can automatically grow as more characters are added.
  • Useful for repeated operations: It is suitable for concatenating or modifying text repeatedly, especially in loops.

Limitations of StringBuilder

  • Not thread-safe by default: Concurrent modifications require appropriate synchronization.
  • Additional memory usage: It maintains an internal character buffer, which may use more memory than necessary if an unnecessarily large capacity is allocated.
  • Conversion may be required: Use ToString() when a regular string is needed, such as when calling an API that expects a string.

StringBuilder Vs String

The following table highlights the differences between String and StringBuilder in C#.

Feature

String

StringBuilder

Mutability

Immutable; its contents cannot be changed after creation.

Mutable; its contents can be modified.

Modification

Operations that change text produce a new string value.

Methods modify the existing builder's content.

Performance

Can be less efficient for repeated modifications.

Often more efficient for repeated modifications.

Namespace

System

System.Text

Use case

Fixed text and simple string operations.

Frequent string modifications, such as repeated appending in loops.

Comment

Explore