2

Possible Duplicate:
best way to clear contents of .NET’s StringBuilder

Is there a quick and easy way to get rid of what a StringBuilder currently holds?

I was looking for a Clear() method but I can't find it. ;)

I would to do

stringBuilderObject = ""

or something along those lines.

Community
  • 1
  • 1
bobber205
  • 12,948
  • 27
  • 74
  • 100
  • @Your comment in JayZengs answer: I think with Length = 0, it will likely re-use the memory that was allocated to it previously, so there shouldn't be an issue. To check this, try using Length = 0, and then check the capacity, it should be the same as it was before you set the length to zero, which is a good thing if you are going to be creating many strings of similar sizes. – Tom Neyland Dec 17 '09 at 02:18
  • Duplicate http://stackoverflow.com/questions/1709471/best-way-to-clear-contents-of-nets-stringbuilder – John Lemp Dec 17 '09 at 01:55

5 Answers5

13

This will do it

stringBuilderObject.Length = 0;
Tom Neyland
  • 6,860
  • 2
  • 36
  • 52
6
stringBuilderObject.Remove(0, stringBuilderObject.Length)
Jay Zeng
  • 1,423
  • 10
  • 10
  • This is what I ended up going with but I may go to the Length = 0. Though that seems like it might have memory issues? – bobber205 Dec 17 '09 at 02:09
  • @bobber205: From http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.remove.aspx: "The current method removes the specified range of characters from the current instance. [...] and the string value of the current instance is shortened by length. The capacity of the current instance is unaffected." So, your memory issues are unaffected by choosing this method over StringBuilder.Length = 0; If you're worried about memory, you need to set StringBuilder.Capacity = some_small_number as well. – Dathan Dec 17 '09 at 13:36
3
stringBuilderObject = new StringBuilder();  // Let the GC do its job
Ana Betts
  • 73,868
  • 16
  • 141
  • 209
  • 1
    Having to reallocate a string builder object may be as bad as just trying to use a normal string performance wise, depending on how its being used and why its being cleared. – Tom Neyland Dec 17 '09 at 01:57
  • 4
    That was my first thought, too. But what about the (albeit probably uncommon) case where a StringBuilder is passed as an argument to a method? Your version doesn't do the trick, whereas stringBuilder.Remove(0, stringBuilder.Length) always works. – Dathan Dec 17 '09 at 01:57
1

This should do it ;)

myStringBuilder = new StringBuilder();
womp
  • 115,835
  • 26
  • 236
  • 269
  • Having to reallocate a string builder object may be as bad as just trying to use a normal string performance wise, depending on how its being used and why its being cleared. – Tom Neyland Dec 17 '09 at 01:56
1
stringBuilderObject.Remove(0,stringBuilderObject.Length)
Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82
expedient
  • 608
  • 4
  • 7