Reputation: 10237
I've been creating dynamic strings to append to a StringBuilder like so:
StringBuilder sb = new StringBuilder();
string bla = "bla";
sb.AppendLine(string.Format("android:id=\"@+id/{0}\" ", bla));
...but then I noticed that StringBuilder has an AppendFormat() method, which obviates the "string.Format()". So I wondered if AppendFormat() also adds a newline, as AppendLine() does (as opposed to Append(), which doesn't).
IOW, to achieve the same effect as:
sb.AppendLine(string.Format("android:id=\"@+id/{0}\" ", bla));
...when using AppendFormat(), would I need to use two lines, like so:
sb.AppendFormat("android:id=\"@+id/{0}\" ", bla);
sb.AppendLine();
?
The answer is yes - two lines are needed, or I must revert to explicitly using string.Format() within a call to AppendLine().
Actually, there is at least one way this can be accomplished in one line with AppendFormat(), to wit:
sb.AppendFormat("android:id=\"@+id/{0}\" {1}", bla, Environment.NewLine);
...but that is arguably no more elegant than than AppendLine(string.Format(...
So which of the following is better (more performant) or safer, or does it not matter?
sb.AppendFormat("android:id=\"@+id/{0}\" {1}", bla, Environment.NewLine);
sb.AppendLine(string.Format("android:id=\"@+id/{0}\" ", bla));
Upvotes: 3
Views: 2558
Reputation: 12797
The most readable is:
sb.AppendFormat("android:id=\"@+id/{0}\" ", bla)
.AppendLine();
string.Format uses StringBuilder
internally, so I wouldn't go with sb.AppendLine(string.Format())
.
Upvotes: 3
Reputation: 203821
Just create your own extension method that calls both AppendLine
and AppendFormat
, to create the method that you want, the ability to append a line using a format string without explicitly adding the new line character:
public static StringBuilder AppendLineFormat(
this StringBuilder builder,
string formatString,
params object[] args)
{
return builder.AppendFormat(formatString, args)
.AppendLine();
}
(Feel free to create an overload of this for each overload of AppendFormat
, if you want to.)
Upvotes: 5