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: , ,

3 Thoughts.

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

Comments are closed.