A recent question came up about using String.Format(). Part of my answer included a suggestion to use StringBuilder.AppendLine(string.Format(...)). Jon Skeet suggested this was a bad example and proposed using a combination of AppendLine and AppendFormat.
It occurred to me I've never really settled myself into a "preferred" approach for using these methods. I think I might start using something like the following but am interested to know what other people use as a "best practice":
sbuilder.AppendFormat("{0} line", "First").AppendLine();
sbuilder.AppendFormat("{0} line", "Second").AppendLine();
// as opposed to:
sbuilder.AppendLine( String.Format( "{0} line", "First"));
sbuilder.AppendLine( String.Format( "{0} line", "Second"));
I view AppendFormat
followed by AppendLine
as not only more readable, but also more performant than calling AppendLine(string.Format(...))
.
The latter creates a whole new string and then appends it wholesale into the existing builder. I'm not going to go as far as saying "Why bother using StringBuilder then?" but it does seem a bit against the spirit of StringBuilder.