C# StringBuilder Clear Method

Letters of the alphabet: ABC

You are using a StringBuilder instance and want to erase all the data from the StringBuilder. By using the Clear() method from the .NET Framework 4.0, you can forget the data in the StringBuilder without allocating anything.

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.

This C# example uses the Clear method on the StringBuilder type.

Program that demonstrates Clear method [C#]

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

Implementation

.NET Framework information

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 of Clear in IL Disassembler and found that it simply assigns the Length property to zero internally. The "return this" part means you can call another method chained after Clear() in the same statement.

Summary

With the Clear method on the StringBuilder type, you have an efficient way of erasing the data stored inside the StringBuilder. Though it simply sets the Length property to zero internally, this method is simpler to use in code than the Length property.

StringBuilder Secrets
.NET