Monday, June 20, 2011

StringBuilder clear method


String builder does not have a clear method to clear the contents of stringBuilder, but if we want to add a clear method in StringBuilder, use the following method in your utility class.

 

    public static void Clear(this StringBuilder stringBuilder)

    {

      stringBuilder.Length = 0;

      stringBuilder.Capacity = 16;

    }

 

Benefit of this method is if we use same stringbuilder variable with clear the existing contents.

Like

 

StringBuilder sb =new StringBuilder();

Sb.append("abc xyz");

 

// If you want to clear the content of sb then

sb.Clear();

 

This should be provided by Microsoft by default because if we re-init the string builder variable every time when we want to clear the content it will take lots of memory.

No comments:

Post a Comment