StringBuilder
The string
class provides many capabilities for processing string
s. However a string
’s contents can never change. Operations that seem to concatenate string
s are in fact creating new string
s—the +=
operator creates a new string
and assigns its reference to the variable on the left of the +=
operator.
The next several sections discuss the features of class StringBuilder
(namespace System.Text
), used to create and manipulate dynamic string information—i.e., mutable strings. Every StringBuilder
can store a certain number of characters that’s specified by its capacity. Exceeding the capacity of a StringBuilder
causes the capacity to expand to accommodate the additional characters. As we’ll see, members of class StringBuilder
, such as methods Append
and AppendFormat
, can be used for concatenation like the operators +
and +=
for class string
—without creating any new string
objects. StringBuilder
is particularly useful for manipulating in place a large number of string
s, as it’s much more efficient than creating individual immutable string
s.
Objects of class string
are immutable (i.e., constant strings), whereas objects of class StringBuilder
are mutable. C# can perform certain optimizations involving string
s (such as the sharing of one string
among multiple references), because it knows these objects will not change.
StringBuilder
ConstructorsClass StringBuilder
provides six overloaded constructors. Class StringBuilderConstructor
(Fig. 16.9) demonstrates three of these overloaded constructors. Line 10 employs the no-parameter StringBuilder
constructor to create a StringBuilder
that contains no characters and has an implementation-specific default initial capacity. Line 11 uses the StringBuilder
constructor that takes an int
argument to create a StringBuilder
that contains no characters and has the initial capacity specified in the int
argument (i.e., 10
). Line 12 uses the StringBuilder
constructor that takes a string
argument to create a StringBuilder
containing the characters of the string
argument—the initial capacity might differ from the string
’s size. Lines 14–16 implicitly use StringBuilder
method ToString
to obtain string
representations of the StringBuilder
s’ contents.