Wednesday 5 December 2012

Reusing a StringBuffer over and over

I wanted to use a StringBuffer instead of a String in order to construct Debug messages in my C# code.

But how to use the same StringBuffer object over and over again within the same method?

The best solution I came up with is to set the length to 0 after use.  Then I can reuse the StringBuffer over and over again

As an example:

StringBuffer sb = new StringBuffer();
log.Debug(sb.Append("Message here: " + var1 + ", " + var2 + "."));
sb.Length=0;
log.Debug(sb.Append("Another message" + var 3 + ", " + var 4 + "."));
sb.Length=0;

Maybe that helps someone.

No comments:

Post a Comment