Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata