TheDeveloperBlog.com


C# StringBuilder Clear Method

Clear erases the character data from a StringBuilder instance. It is found in the .NET Framework 4.0. We can forget the data in the StringBuilder without allocating anything. This can lead to performance enhancements.

Tip: Clear internally sets the Length of the StringBuilder to zero. It provides a "clearer" syntax for this operation.


Example. To start, this program appends ten digits to a StringBuilder. Then, it displays the Length of the buffer. Next, the Clear instance method is invoked, and finally the Length is displayed again: it is now zero.

C# program that demonstrates Clear method

using System;
using System.Text;

class Program
{
    static void Main()
    {
	var builder = new StringBuilder();
	for (int i = 0; i < 10; i++)
	{
	    builder.Append(i);
	}
	Console.WriteLine("Before Clear(): {0}", builder.Length);
	builder.Clear();
	Console.WriteLine("After Clear(): {0}", builder.Length);
    }
}

Output

Before Clear(): 10
After Clear(): 0


Internals. In the release notes for the .NET Framework 4.0, the Clear method is one of the new features. Out of interest, I opened the implementation in IL Disassembler. I found that Clear simply assigns the Length property to zero internally.

Note: The "return this" part means you can call another method chained after Clear() in the same statement.

Return StatementThis Instance

Tip: Other methods on the StringBuilder also return the StringBuilder reference. More examples of this pattern are available.


Summary. With the Clear method on the StringBuilder type, you have an efficient way of erasing the data stored inside the StringBuilder. It simply sets the Length property to zero internally. But this method is simpler than the Length property.