Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make StringBuilder empty again in .NET 3.5 ?

I have a loop where i create some string value based on certain conditions. I did place StringBuilder object outside of the loop and each time i have new row in loop i need to clear StringBuilder appended values for this row.

How do i clear those?

        StringBuilder sb = new StringBuilder();

        foreach (DataRow row in recipientsList.Rows)
        {
            sb.Length = 0;
            sb.Append("<ul>");
            if (row["needsToActivate"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutActivationTemplate());
            }
            if (row["needsToEnterSite"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutEnteringWebsiteForTwoWeeksTemplate());
            }
            if (row["needsPicture"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutPicturesTemplate());
            }
            if (row["needsText"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutTextTemplate());
            }
            if (row["needsCharacteristic"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutCharateristicsTemplate());
            }
            if (row["needsHobby"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutHobbiesTemplate());
            }
            sb.Append("</ul>");
}

Code with accepted answer;

like image 912
eugeneK Avatar asked Jul 12 '10 09:07

eugeneK


People also ask

How do you make empty StringBuilder?

You should use sb. delete(0, sb. length()) or sb. setLength(0) and NOT create a new StringBuilder().

How do I know if my StringBuilder is empty?

Check if StringBuilder Is Empty Using the Length Property The StringBuilder class has a property named Length that shows how many Char objects it holds. If Length is zero that means the instance contains no characters.

Is StringBuilder still necessary?

Fortunately, you don't need to use StringBuilder anymore - the compiler can handle it for you. String concatenation has always been a well-discussed topic among Java developers. It's been costly.

Is there a StringBuilder in C#?

C# StringBuilder is similar to Java StringBuilder. A String object is immutable, i.e. a String cannot be changed once created. Every time when you use any of the methods of the System. String class, then you create a new string object in memory.


1 Answers

You can simply;

sb.Length = 0;
like image 157
Alex K. Avatar answered Oct 03 '22 10:10

Alex K.