Information Technology Reference
In-Depth Information
last technique involves building the final value for immutable types. The
System.String class is immutable: After you construct a string, the con-
tents of that string cannot be modified. Whenever you write code that
appears to modify the contents of a string, you are actually creating a new
string object and leaving the old string object as garbage. This seemingly
innocent practice:
string
msg =
"Hello, "
;
msg += thisUser.Name;
msg +=
". Today is "
;
msg += System.
DateTime
.Now.ToString();
is just as inefficient as if you had written this:
string
msg =
"Hello, "
;
// Not legal, for illustration only:
string
tmp1 =
new
String
(msg + thisUser.Name);
msg = tmp1;
// "Hello " is garbage.
string
tmp2 =
new
String
(msg +
". Today is "
);
msg = tmp2;
// "Hello <user>" is garbage.
string
tmp3 =
new
String
(msg +
DateTime
.Now.ToString());
msg = tmp3;
// "Hello <user>. Today is " is garbage.
The strings tmp1, tmp2, and tmp3, and the originally constructed msg
("Hello"), are all garbage. The
+=
method on the string class creates a new
string object and returns that string. It does not modify the existing string
by concatenating the characters to the original storage. For simple con-
structs such as the previous one, you should use the string.Format()
method:
string
msg =
string
.Format(
"Hello, {0}. Today is {1}"
,
thisUser.Name,
DateTime
.Now.ToString());
For more complicated string operations, you can use the StringBuilder
class:
StringBuilder msg =
new
StringBuilder(
"Hello, "
);
msg.Append(thisUser.Name);
msg.Append(
". Today is "
);
msg.Append(
DateTime
.Now.ToString());
string
finalMsg = msg.ToString();
StringBuilder is the mutable string class used to build an immutable string
object. It provides facilities for mutable strings that let you create and