CTS System::String and System::Text::StringBuilder

Any System::String object is immutable. That means, for instance, that calling String::Concat() does not change the passed object, but return a newly allocated System::String.

Here is a short example that should clarify how System::String works:

System::String^ str1 = System::String::Empty; // 1.
str1 += "a";
str1 = str1 + "a";
str1 = System::String::Concat(str1, "a");
System::Console::WriteLine(str1); // 2.
System::String^ str2 = str1->ToUpper();
System::Console::WriteLine(str2); // 3.

1. overkilling, Concat() is smart enough to manage nullptr System::String in input
2. the three lines before have the same effect, so now we have "aaa" in str1
3. notice that ToUpper() does not change str1, it just creates a new System::String

To avoid the creation of many unncecessary temporary strings is often useful using System::Text::StringBuilder, a sort of mutable string. It coulb be used in this way:

using System::Text::StringBuilder;
StringBuilder^ sb = gcnew StringBuilder(1024);
sb->Append("Rows: \n");
for (int i = 0; i < 100; ++i)
sb->AppendFormat("Row {0}\n", i);
System::String^ str3 = sb->ToString();

This post is based on my reading on the book "Expert C++/CLI: .NET for Visual C++ Programmers" by Marcus Heege, APress.

No comments:

Post a Comment