Home

Search

C# StringBuilder Clear (Set Length to Zero)

Use the Clear method on the StringBuilder type. Test the Length of a StringBuilder.

dot net perls

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.StringBuilder

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.
Tip: Clear internally sets the Length of the StringBuilder to zero. It provides a "clearer" syntax for this operation.
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.
ReturnThis
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.

Home

© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.