C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: Because many .NET programs use a string parameter type, converting the StringBuilder's buffer to a string is useful.
Main: This method creates a StringBuilder and appends 13 strings to its buffer using the Append calls.
Finally: We call ToString. This method internally uses logic and often does not copy the string data an additional time.
Instead: ToString sets a null character in the buffer data and transforms the buffer into a string without any allocation occurring.
C# program that uses ToString method on StringBuilder
using System;
using System.Text;
class Program
{
static void Main()
{
//
// Begin by declaring a StringBuilder and adding three strings.
//
StringBuilder builder = new StringBuilder();
builder.Append("one ");
builder.Append("two ");
builder.Append("three ");
//
// Add many strings to the StringBuilder in a loop.
//
for (int i = 0; i < 10; i++)
{
builder.Append("x ");
}
//
// Get a string from the StringBuilder.
// ... Often no additional copying is required at this stage.
//
string result = builder.ToString();
Console.WriteLine(result);
}
}
Output
one two three x x x x x x x x x x
Note: An additional copy of the string characters is made when the StringBuilder is being used on multiple threads at the same time.
However: In all other cases, the ToString method simply modifies its internal buffer and transforms it into a string.