How to append two stringBuilders?
I know this is three years later, but the .NET 4 StringBuilder
behaves differently anyway.
Nevertheless, it does still come back to "what do you want to do?" Are you looking for simply the most performant way of appending two StringBuilders
and continuing on with just the latter result? Or are you expecting to continue working with the existing buffered value of the appended StringBuilder
?
For the former, and always in .NET 4,
frontStringBuilder.Append(backStringBuilder);
is best.
For the latter scenario in .NET 2/3.5,
frontStringBuilder.Append(backStringBuilder.ToString(0, backStringBuilder.Length));
is best (and won't hurt performance in .NET 4).
Just like that....
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
sb.Append(sb1.ToString());
This will do it without allocations
StringBuilder sb = new StringBuilder("aaaa");
StringBuilder second = new StringBuilder("bbbbb");
sb.EnsureCapacity(sb.Length + second.Length);
for (int i = 0; i < second.Length; i++)
{
sb.Append(second[i]);
}