Three Ways to Clear a StringBuilder

by bob on June 11, 2007

Here’s a micro-pattern that can show up sometimes in string processing: a StringBuilder is created, and then in a loop some sort of string is built with repeated Append() calls (or with the much under-used AppendFormat() method). The string is then pulled out and consumed by something else, the StringBuilder is emptied and re-used on the next iteration.

For some reason there is no Clear() method on a StringBuilder. I always thought this odd. I’ve generally used:

someStringBuilder.Remove(0,someStringBuilder.Length);

Today, trying to tighten something time-critical, I ran across:

string theString = someStringBuilder.ToString();
someStringBuilder.Replace(theString,"");

I was about to replace this with my usual Remove() call, figuring that eliminating the string matching would be a performance win, when on a sudden impulse I tried this:

someStringBuilder.Length = 0;

Lo and behold, the Length property is not read-only. No wonder there is no Clear() method; one isn’t really needed, except maybe to make how to do this more obvious.