StringBuilder has a reputation for being a faster string processing tool than just string concatenation. Regardless of whether this is true, I have to wonder about the results of StringBuilder operations and the strings they produce.
A quick walk in Reflector shows that StringBuilder.ToString () does not always return a copy, sometimes it seems that it returns an instance of the internal string. It also seems to use some internal functions to manipulate internal strings.
So what will I get if I do this?
string s = "Yo Ho Ho"; StringBuilder sb = new StringBuilder(s); string newString = sb.ToString(); sb.Append(" and a bottle of rum."); string newNewString = sb.ToString();
Are newString and newNewString different string instances or the same? I tried to understand this through a reflector, and I just do not quite understand everything.
How about this code?
StringBuilder sb = new StringBuilder("Foo\n"); StringReader sr = new StringReader(sb.ToString()); string s = sr.ReadLine(); sb.Append("Bar\n"); s = sr.ReadLine();
Will the last statement return null or "Bar"? And if it returns one or the other, is it defined or undefined behavior? In other words, can I rely on this?
The documentation is noteworthy on this point, and I reluctantly rely on observed behavior by specification.
Erik funkenbusch
source share