Setting the Maximum Number of Characters a StringBuilder Can Contain






Setting the Maximum Number of Characters a StringBuilder Can Contain

Problem

You want to insure that the data assigned to a StringBuilder object does not exceed a certain number of characters.

Solution

Use the overloaded constructor of the StringBuilder class, which accepts a parameter 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 prevent 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 identical. This way gives you the best performance, overall. If these two parameters are not identical, it is critical that they can coexist. The following line of code:

	System.Text.StringBuilder sbMax = new System.Text.StringBuilder(30, 12);

will throw an ArgumentOutOfRangeException. The reason is that the initialCapacity parameter is larger than maxCapacity, causing the exception. While you may not be explicitly writing these values for your application, if you are calculating them using some type of expression, you may run into these problems.

To handle an attempt to append characters to the StringBuilder string, forcing it beyond the maximum size, wrap any code to append text to the StringBuilder object in a try-catch block:

	try
	{
	    sbMax.Append("New String");
	}
	catch(ArgumentOutOfRangeException rangeE)
	{
	    // Handle overrun here.
	}

In addition to the Append method, you should also wrap any AppendFormat, Insert, and Replace methods of the StringBuilder object in a try-catch block. Any of these methods can allow characters to be added to the StringBuilder string, potentially causing its length to exceed its maximum specified length.

See Also

See the "StringBuilder.Append Method" topic in the MSDN documentation.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows