Framework Tips I: Clear StringBuilder

StringBuilder is a class that allows you to manipulate strings in mutable manner. It has many methods allowing you to Append, Insert and Replace, portions of the string. However it does not contain Clear() method, that would allow you to clear the content of a StringBuilder.
There is Remove(int,int) method, that allows you to do this, but it requires you to pass two parameters to achieve this.

int startIndex = 0;

stringBuilder.Remove(startIndex, stringBuilder.Length);

There is however easier, and more elegant way to do this. Other than in case of most classes in the framework, StringBuilder’s Length property is writable, so you can simply write:

stringBuilder.Length = 0;

Technorati Tags: , ,


Alan says:

One elegant way to add the Clear() method to StringBuilder is to use the Method Extensions.

stephen says:

Brilliant, no need to write an extension method for the String Builder class then to take care of this in one line!

Matt says:

This is also faster than .remove so highly recommended! Especially if your sb is in a loop