O'Reilly logo

Visual Basic 2008 Recipes: A Problem-Solution Approach by Rakesh Rajan, Matthew MacDonald, Allen Jones, Todd Herman

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.1. Manipulate the Contents of a String Efficiently

Problem

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.

Solution

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

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