StringBuilder Class

Updated: March 2012

Represents a mutable string of characters. This class cannot be inherited.

Namespace:  System.Text
Assembly:  mscorlib (in mscorlib.dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class StringBuilder : ISerializable

This class represents a string-like object whose value is a mutable sequence of characters. The value is said to be mutable because it can be modified once it has been created by appending, removing, replacing, or inserting characters. For comparison, see the String class.

Most of the methods that modify an instance of this class return a reference to that same instance. Since a reference to the instance is returned, you can call a method or property on the reference. This can be convenient if you want to write a single statement that chains successive operations one after another.

The capacity of a StringBuilder is the maximum number of characters the instance can store at any given time, and is greater than or equal to the length of the string representation of the value of the instance. The capacity can be increased or decreased with the Capacity property or EnsureCapacity method, but it cannot be less than the value of the Length property.

Implementation-specific default values are used if no capacity or maximum capacity is specified when an instance of StringBuilder is initialized.

Performance Considerations

The Concat and AppendFormat methods both concatenate new data to an existing String or StringBuilder object. A String object concatenation operation always creates a new object from the existing string and the new data. A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.

The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.

Memory Allocation

The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue.

A StringBuilder object can allocate more memory to store characters when the value of an instance is enlarged, and the capacity is adjusted accordingly. The amount of memory allocated is implementation-specific, and an ArgumentOutOfRangeException exception is thrown if the amount of memory required is greater than the maximum capacity.

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note: Continuously appending strings to StringBuilder objects can result in virtual address space fragmentation. Due to the limited virtual address space for each process in Windows CE, this issue can appear after appending strings of approximately 3 MB. To workaround this issue, you can set the MaxCapacity property. Alternatively, open a MemoryStream and write strings to the memory stream instead of using the StringBuilder class.

The following example shows how to call many of the methods defined by the StringBuilder class.

using System;
using System.Text;

public sealed class App 
{
    static void Main() 
    {
        // Create a StringBuilder that expects to hold 50 characters. 
        // Initialize the StringBuilder with "ABC".
        StringBuilder sb = new StringBuilder("ABC", 50);

        // Append three characters (D, E, and F) to the end of the StringBuilder.
        sb.Append(new char[] { 'D', 'E', 'F' });

        // Append a format string to the end of the StringBuilder.
        sb.AppendFormat("GHI{0}{1}", 'J', 'k');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

        // Insert a string at the beginning of the StringBuilder.
        sb.Insert(0, "Alphabet: ");

        // Replace all lowercase k's with uppercase K's.
        sb.Replace('k', 'K');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());
    }
}

// This code produces the following output. 
// 
// 11 chars: ABCDEFGHIJk 
// 21 chars: Alphabet: ABCDEFGHIJK

System.Object
  System.Text.StringBuilder

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Date

History

Reason

March 2012

Added information about memory allocation to Remarks section.

Information enhancement.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft