System.Text.StringBuilder Class

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

See Also: StringBuilder Members


public sealed class StringBuilder : System.Runtime.Serialization.ISerializable


This class represents a string-like object whose value is a mutable sequence of characters.

In this section:

The String and StringBuilder types

Although System.Text.StringBuilder and string both represent sequences of characters, they are implemented differently. string is an immutable type. That is, each operation that appears to modify a string object actually creates a new string.

For example, the call to the string.Concat(String[]) method in the following C# example appears to change the value of a string variable named value. In fact, the string.Concat(String[]) method returns a value object that has a different value and address from the value object that was passed to the method. Note that the example must be compiled using the /unsafe compiler option.

code reference: System.Text.StringBuilder.Class#1

For routines that perform extensive string manipulation (such as apps that modify a string numerous times in a loop), modifying a string repeatedly can exact a significant performance penalty. The alternative is to use System.Text.StringBuilder, which is a mutable string class. Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. A System.Text.StringBuilder object maintains a buffer to accommodate expansions to the string. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.


Although the System.Text.StringBuilder class generally offers better performance than the string class, you should not automatically replace string with System.Text.StringBuilder whenever you want to manipulate strings. Performance depends on the size of the string, the amount of memory to be allocated for the new string, the system on which your app is executing, and the type of operation. You should be prepared to test your app to determine whether System.Text.StringBuilder actually offers a significant performance improvement.

Consider using the string class under these conditions:

Consider using the System.Text.StringBuilder class under these conditions:

How StringBuilder works

The StringBuilder.Length property indicates the number of characters the System.Text.StringBuilder object currently contains. If you add characters to the System.Text.StringBuilder object, its length increases until it equals the size of the StringBuilder.Capacity property, which defines the number of characters that the object can contain. If the number of added characters causes the length of the System.Text.StringBuilder object to exceed its current capacity, new memory is allocated, the value of the StringBuilder.Capacity property is doubled, new characters are added to the System.Text.StringBuilder object, and its StringBuilder.Length property is adjusted. Additional memory for the System.Text.StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.MaxCapacity property. When the maximum capacity is reached, no further memory can be allocated for the System.Text.StringBuilder object, and trying to add characters or expand it beyond its maximum capacity throws either an ArgumentOutOfRangeException or an OutOfMemoryException exception.

The following example illustrates how a System.Text.StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. The code creates a System.Text.StringBuilder object by calling its default (parameterless) constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. Appending the string "This is a sentence." results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the System.Text.StringBuilder object. The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. The code then appends the string "This is an additional sentence." to the value of the System.Text.StringBuilder object 11 times. Whenever the append operation causes the length of the System.Text.StringBuilder object to exceed its capacity, its existing capacity is doubled and the StringBuilder.Append(string) operation succeeds.

code reference: System.Text.StringBuilder.Class#3

Memory allocation

The default capacity of a System.Text.StringBuilder object is 16 characters, and its default maximum capacity is int.MaxValue. These default values are used if you call the StringBuilder.#ctor and StringBuilder.#ctor(string) constructors.

You can explicitly define the initial capacity of a System.Text.StringBuilder object in the following ways:

If the length of the string assigned to the System.Text.StringBuilder object in the constructor call exceeds either the default capacity or the specified capacity, the StringBuilder.Capacity property is set to the length of the string specified with the value parameter.

You can explicitly define the maximum capacity of a System.Text.StringBuilder object by calling the StringBuilder.#ctor(int, int) constructor. You can't change the maximum capacity by assigning a new value to the StringBuilder.MaxCapacity property, because it is read-only.

As the previous section shows, whenever the existing capacity is inadequate, additional memory is allocated and the capacity of a System.Text.StringBuilder object doubles up to the value defined by the StringBuilder.MaxCapacity property.

In general, the default capacity and maximum capacity are adequate for most apps. You might consider setting these values under the following conditions:

Instantiating a StringBuilder object

You instantiate a System.Text.StringBuilder object by calling one of its six overloaded class constructors, which are listed in the following table. Three of the constructors instantiate a System.Text.StringBuilder object whose value is an empty string, but set its StringBuilder.Capacity and StringBuilder.MaxCapacity values differently. The remaining three constructors define a System.Text.StringBuilder object that has a specific string value and capacity. Two of the three constructors use the default maximum capacity of int.MaxValue, whereas the third allows you to set the maximum capacity.







Defined by the capacity parameter


StringBuilder.#ctor(int, int)


Defined by the capacity parameter

Defined by the maxCapacity parameter


Defined by the value parameter

16 or value. string.Length, whichever is greater


StringBuilder.#ctor(string, int)

Defined by the value parameter

Defined by the capacity parameter or value. string.Length, whichever is greater.


StringBuilder.#ctor(string, int, int, int)

Defined by value. string.Substring(int)(startIndex, length)

Defined by the capacity parameter or value. string.Length, whichever is greater.

Defined by the maxCapacity parameter

The following example uses three of these constructor overloads to instantiate System.Text.StringBuilder objects.

code reference: System.Text.StringBuilder.Class#6

Calling StringBuilder methods

Most of the methods that modify the string in a System.Text.StringBuilder instance return a reference to that same instance. This enables you to call System.Text.StringBuilder methods in two ways:

Performing StringBuilder operations

You can use the methods of the System.Text.StringBuilder class to iterate, add, delete, or modify characters in a System.Text.StringBuilder object.

Iterating StringBuilder characters

You can access the characters in a System.Text.StringBuilder object by using the StringBuilder.Chars(int) property. In C#, StringBuilder.Chars(int) is an indexer; in Visual Basic, it is the default property of the System.Text.StringBuilder class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the StringBuilder.Chars(int) property. Characters in a System.Text.StringBuilder object begin at index 0 (zero) and continue to index StringBuilder.Length - 1.

The following example illustrates the StringBuilder.Chars(int) property. It appends ten random numbers to a System.Text.StringBuilder object, and then iterates each character. If the character's Unicode category is System.Globalization.UnicodeCategory.DecimalDigitNumber, it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the System.Text.StringBuilder object both before and after the values of individual characters were changed.

code reference: System.Text.StringBuilder.Class#7

Adding text to a StringBuilder object

The System.Text.StringBuilder class includes the following methods for expanding the contents of a System.Text.StringBuilder object:

The following example uses the StringBuilder.Append(string), StringBuilder.AppendLine, StringBuilder.AppendFormat(string, Object[]), and StringBuilder.Insert(int, string) methods to expand the text of a System.Text.StringBuilder object.

code reference: System.Text.StringBuilder.Class#9

Deleting text from a StringBuilder object

The System.Text.StringBuilder class includes methods that can reduce the size of the current System.Text.StringBuilder instance. The StringBuilder.Clear method removes all characters and sets the StringBuilder.Length property to zero. The StringBuilder.Remove(int, int) method deletes a specified number of characters starting at a particular index position. In addition, you can remove characters from the end of a System.Text.StringBuilder object by setting its StringBuilder.Length property to a value that is less than the length of the current instance.

The following example removes some of the text from a System.Text.StringBuilder object, displays its resulting capacity, maximum capacity, and length property values, and then calls the StringBuilder.Clear method to remove all the characters from the System.Text.StringBuilder object.

code reference: System.Text.StringBuilder.Class#10

Modifying the text in a StringBuilder object

The StringBuilder.Replace(string, string) method replaces all occurrences of a character or a string in the entire System.Text.StringBuilder object or in a particular character range. The following example uses the StringBuilder.Replace(string, string) method to replace all exclamation points (!) with question marks (?) in the System.Text.StringBuilder object.

code reference: System.Text.StringBuilder.Class#11

Searching the text in a StringBuilder object

The System.Text.StringBuilder class does not include methods similar to the string.Contains(string), string.IndexOf(string), and string.StartsWith(string) methods provided by the string class, which allow you to search the object for a particular character or a substring. Determining the presence or starting character position of a substring requires that you search a string value by using either a string search method or a regular expression method. There are four ways to implement such searches, as the following table shows.

Search string values before adding them to the System.Text.StringBuilder object.

Useful for determining whether a substring exists.

Cannot be used when the index position of a substring is important.

Call StringBuilder.ToString and search the returned string object.

Easy to use if you assign all the text to a System.Text.StringBuilder object, and then begin to modify it.

Cumbersome to repeatedly call StringBuilder.ToString if you must make modifications before all text is added to the System.Text.StringBuilder object.

You must remember to work from the end of the System.Text.StringBuilder object's text if you're making changes.

Use the StringBuilder.Chars(int) property to sequentially search a range of characters.

Useful if you're concerned with individual characters or a small substring.

Cumbersome if the number of characters to search is large or if the search logic is complex.

Convert the System.Text.StringBuilder object to a string object, and perform modifications on the string object.

Useful if the number of modifications is small.

Negates the performance benefit of the System.Text.StringBuilder class if the number of modifications is large.

Let's examine these techniques in greater detail.

Converting the StringBuilder object to a string

You must convert the System.Text.StringBuilder object to a string object before you can pass the string represented by the System.Text.StringBuilder object to a method that has a string parameter or display it in the user interface. You perform this conversion by calling the StringBuilder.ToString method. For an illustration, see the previous example, which calls the StringBuilder.ToString method to convert a System.Text.StringBuilder object to a string so that it can be passed to a regular expression method.

Thread Safety

All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe.


Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0,,