Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

StringBuilder Class

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
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class StringBuilder implements ISerializable
SerializableAttribute 
ComVisibleAttribute(true) 
public final class StringBuilder implements ISerializable
Not applicable.

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.

Notes to Implementers: The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue. A StringBuilder can allocate more memory as needed 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 ArgumentOutOfRangeException is thrown if the amount of memory required is greater than the maximum capacity. For example, the Append, AppendFormat, EnsureCapacity, Insert, and Replace methods can enlarge the value of an instance. The individual characters in the value of a StringBuilder can be accessed with the Chars property. Index positions start from zero.

Windows Mobile 2003 for Pocket PC, Windows Mobile 2003 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 code example shows how to call many of the methods defined by the StringBuilder class.

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
               <atlas:ScriptManager runat="server" ID="ScriptManager1">
               </atlas:ScriptManager>
    </form>
</body>
</html>

<script type="text/javascript">

    Type.registerNamespace('Samples');
    Samples.StringBuilderExample = function()
    {
        this._headTagStart = "<head>";
        this._headTagEnd = "</head>";
        this._titleTagStart = "<title>";
        this._titleTagEnd = "</title>";
    }
    Samples.StringBuilderExample.prototype = 
    { 
        buildString: function(title) 
        {
            try
            {
                if (title === undefined) throw Error.argumentUndefined('title');
                if (title === null) throw Error.argumentNull('title');
                
                var sb = new Sys.StringBuilder(this._headTagStart);
                sb.append(this._titleTagEnd);
                sb.append(title);
                sb.append(this._titleTagEnd);
                sb.append(this._headTagEnd);
                // Displays: "The result is: <head><title>A Title</title></head>"
                alert("The result is: " + sb.toString()); 
            }
            catch(e)
            {
                // If debug mode then write extended exception information to the page.
                // Otherwise, show an alert.
                if(debug.isDebug)
                {
                  var msg = "(DEBUG MODE)</p>A CLIENT-SIDE RUNTIME EXCEPTION OCCURED:</p>" + e.message;
                  document.write(msg);
                }
                else
                {
                  alert(e.message);
                }
            }
        }
    }
    
    Samples.StringBuilderExample.registerClass('Samples.StringBuilderExample');
    
    var StringBuilderSampleVar = new Samples.StringBuilderExample();
    var title = "A Title";
    StringBuilderSampleVar.buildString(title);
    
</script>

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 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft