Saturday, March 27, 2010

.NET 4.0- A new method StringBuilder.Clear() to clear stringbuilder

With Microsoft.NET 4.0 we have a convenient method called clear method which will clear string builder. This method is very use full where we need to use string builder for multiple string manipulation. So we don’t need to create a separate string builder for it. Let’s take a simple example which will print string builder string before,after clear so we can see how it works. Following is simple console application for this.

namespace ConsoleApplication1
class Program
static void Main(string[] args)
System.Text.StringBuilder myStringBuilder =
new System.Text.StringBuilder(string.Empty);
myStringBuilder.Append("This is my string");
Console.WriteLine("String Builder Output Before Clear:{0}",
Console.WriteLine("String Builder Output After Clear:{0}",
myStringBuilder.Append("This is my another string");
Console.WriteLine("String Builder Output After new string:{0}",
Here is a output as expected.Strinbuilder

Technorati Tags: ,
Shout it
kick it on


  1. You didn't need to create a new StringBuilder before either. You could set its Length property to 0.

    However, that wasn't very straightforward and not very well known.

  2. Yes, I know that but I am just showcasing the new method which comes with .NET 4.0


Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog


My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews