
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Setting the Maximum Number of Characters a StringBuilder Can Contain
|
69
Solution
Use the overloaded constructor of the StringBuilder class, which accepts a parame-
ter for maximum capacity. The following code creates a
StringBuilder object that
has a maximum size of 10 characters:
System.Text.StringBuilder sbMax = new System.Text.StringBuilder(10, 10);
sbMax.Append("123456789");
sbMax.Append("0");
This code creates a StringBuilder object, sbMax, which has a maximum length of 10
characters. Nine characters are appended to this string and then a tenth character is
appended without a problem. However, if the next line of code is executed:
sbMax.Append("#");
the length of sbMax goes beyond 10 characters and an ArgumentOutOfRangeException is
thrown.
Discussion
The string object is immutable and, as such, has no use for a built-in method to pre-
vent its length from going beyond a certain point. Fortunately, the
StringBuilder
object contains an overloaded constructor that allows the maximum size of its string
to be set. The
StringBuilder constructor that you are concerned with is defined as
follows:
public StringBuilder(int initialCapacity, int maxCapacity)
For most applications, the initialCapacity and maxCapacity parameters can be iden-
tical. This way gives you the best performance, overall. If ...