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.
static void Main()
// Begin by declaring a StringBuilder and adding three strings.
//StringBuilder builder = new StringBuilder();
// Add many strings to the StringBuilder in a loop.
//for (int i = 0; i < 10; i++)
// Get a string from the StringBuilder.
// ... Often no additional copying is required at this stage.
string result = builder.ToString();
}one two three x x x x x x x x x x
Discussion. 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.
Note An additional copy of the string characters is made when the StringBuilder is being used on multiple threads at the same time.
Note 2 An additional copy is also made if the memory allocated to the StringBuilder is much larger than required.
Info This improves efficiency. It means that the copy will occupy less memory in the long run.
However In all other cases, the ToString method simply modifies its internal buffer and transforms it into a string.
Summary. We examined the StringBuilder ToString method. This converts the character buffer to a string. ToString internally prevents an extra string copy from occurring.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 12, 2022 (edit link).