Wednesday 4 July 2012

.Net Tips : new Clear Method Introduce in StringBuilder Class in .Net Framework 4 with C# Examples and VB.Net Examples

In  .NET Framework 4 New Method introduce in StringBuilder class. Method name is "Clear". This method helps you to clear or remove values or data from String Builder object's.
In earlier version of .Net , If you want to remove values or data from string builder object's for next use , at that time you want to set Length Property to Zero.

Syntax
     objStringBuilder.Length=0

But now in .Net 4.0 framework , you have to call Clear method.

Here are example for this.
In this example we set some values using Append methods to string builder after that we print this value , after that we clear string builder object and again we insert some value in string builder and print this.
You can see that when second time we print string builder object value it does not contains previous value. This previous values remove by Clear Method.

C# Example :
        System.Text.StringBuilder objSB = new System.Text.StringBuilder();
        //Append values
        objSB.Append("This is .Net Blog.");
        objSB.Append("You can get latest C# Tips over here.");

        //Display on screen
        Response.Write(objSB.ToString());
        Response.Write("<br/><br/>");

        //Clear object using Clear method
        objSB.Clear();

        //Append another values
        objSB.Append("This blog is very useful for .Net Beginners");

        Response.Write("After Clear<br/><br/>");
        //Display on screen
        Response.Write(objSB.ToString());


VB.net Example :
        Dim objSB As New System.Text.StringBuilder()
        'Append values
        objSB.Append("This is .Net Blog.")
        objSB.Append("You can get latest C# Tips over here.")

        'Display on screen
        Response.Write(objSB.ToString())
        Response.Write("<br/><br/>")

        'Clear object using Clear method
        objSB.Clear()

        'Append another values
        objSB.Append("This blog is very useful for .Net Beginners")

        Response.Write("After Clear<br/><br/>")
        'Display on screen
        Response.Write(objSB.ToString())

Output :


This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that. 


No comments:

Post a Comment