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}",
myStringBuilder.ToString());
myStringBuilder.Clear();
Console.WriteLine("String Builder Output After Clear:{0}",
myStringBuilder.ToString());
myStringBuilder.Append("This is my another string");
Console.WriteLine("String Builder Output After new string:{0}",
myStringBuilder.ToString());
}
}
}
Technorati Tags: ASP.NET4.0,C#.NET4.0
You didn't need to create a new StringBuilder before either. You could set its Length property to 0.
ReplyDeleteHowever, that wasn't very straightforward and not very well known.
Yes, I know that but I am just showcasing the new method which comes with .NET 4.0
ReplyDelete