O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.19. Setting the Maximum Number of Characters a String Can Contain

Problem

You want to ensure that the data entered by a user and assigned to a string does not exceed a certain number of characters.

Solution

Use the overloaded constructor of the StringBuilder class, which accepts a 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, does not have 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 we are concerned with is defined as follows:

public StringBuilder(int initialCapacity, int maxCapacity)

For most applications, the initialCapacity and maxCapacity can be identical. This way gives you the best performance, overall. If these two parameters are not identical, it is critical that these two parameters can coexist. Take, for ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required