Building Strings

Building Strings

 

String is an extremely powerful class that implements a large number of very useful

methods. However, the String class has a shortcoming that makes it very inefficient for making

repeated modifications to a given string — it is actually an immutable data type, which means that once

you initialize a string object, that string object can never change. The methods and operators that appear

to modify the contents of a string actually create new strings, copying across the contents of the old

 

string if necessary. For example, look at the following code:

 

string greetingText = “Hello from all the guys at  Awa Blog. “;

 

greetingText += “We do hope you enjoy this blog as much as myself enjoyed writing it.”;

 

What happens when this code executes is this: first, an object of type System.String is created and

initialized to hold the text Hello from all the guys at Awa Blog. . Note the space after the

period. When this happens, the .NET runtime allocates just enough memory in the string to hold this

text (39 chars), and the variable greetingText is set to refer to this string instance.

In the next line, syntactically it looks like more text is being added onto the string — though it is not.

Instead, what happens is that a new string instance is created with just enough memory allocated to

store the combined text — that ' s 103 characters in total. The original text, Hello from all the

guys at Awa Blog. , is copied into this new string instance along with the extra text, We do hope

you enjoy this blog  as much as myself enjoyed writing it. . Then, the address stored in the

variable greetingText is updated, so the variable correctly points to the new String object. The old

String object is now unreferenced — there are no variables that refer to it — and so will be removed the

next time the garbage collector comes along to clean out any unused objects in your application.

 

Ebook Download
View all
Learn
View all