2.1. Manipulate the Contents of a String Efficiently


You need to manipulate the contents of a String object and want to avoid the overhead of automatic String creation caused by the immutability of String objects.


Use the System.Text.StringBuilder class to perform the manipulations and convert the result to a String object using the StringBuilder.ToString method.

How It Works

String objects in .NET are immutable, meaning that once they are created, their content cannot be changed. If you build a string by concatenating a number of characters or smaller strings, the common language runtime (CLR) will create a completely new String object whenever you add a new element to the end of the existing string. Here is an example:

Dim ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.