StringBuilder
ToString
ToString
on StringBuilder
returns a string
. It internally converts the character buffer of the StringBuilder
into a string
object.
ToString
does this without allocating memory or copying a lot of data in most cases. It often has no significant performance penalty.
This program demonstrates the ToString
method on StringBuilder
. This method is used to convert a StringBuilder
's character buffer into an actual string
reference.
string
parameter type, converting the StringBuilder
's buffer to a string
is useful.StringBuilder
and appends 13 strings to its buffer using the Append
calls.ToString
. This method internally uses logic and often does not copy the string
data an additional time.ToString
sets a null
character in the buffer data and transforms the buffer into a string
without any allocation occurring.using System; using System.Text; // // 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);one two three x x x x x x x x x x
Does ToString()
actually make another copy of the string
data? The ToString
method on StringBuilder
contains some logic that avoids an additional copy in many cases.
string
characters is made when the StringBuilder
is being used on multiple threads at the same time.StringBuilder
is much larger than required.ToString
method simply modifies its internal buffer and transforms it into a string
.We examined the StringBuilder
ToString
method. This converts the character buffer to a string
. ToString
internally prevents an extra string
copy from occurring.