You want to rewrite your StringBuilder code to be more succinct and easier to read. Instead of using dozens of Append lines, you want to combine the StringBuilder Append calls. Here we see how you can chain StringBuilder Append calls, resulting in clearer and shorter code.
To start, we see how many developers use StringBuilder. Remember that StringBuilder often improves your application's performance, and is a very important part of your tool belt as a developer. Here's some sample StringBuilder code that uses the regular syntax.
=== Program that uses Append syntax (C#) ===
using System.Text;
class Program
{
static void Main()
{
// Conventional StringBuilder syntax.
const string s = "Value";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
builder.Append("One string ");
builder.Append(s);
builder.Append("Another string");
}
}
}
=== Program that uses altenative Append syntax (C#) ===
using System.Text;
class Program
{
static void Main()
{
// This is a fluent interface for StringBuilder.
const string s = "Value";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
builder.Append("One string ").Append(s).Append("Another string");
}
}
}Chaining StringBuilder methods. Here we look at how you can combine multiple Append calls into a single statement. StringBuilder's Append() method returns a reference to itself. The designers of C# foresaw the problem with repetitive StringBuilder appends. They are ugly and verbose, and thus prone to errors. Here we chain StringBuilder Append calls.
Another option when you want to Append string together is to just use the + plus operator on the string type. Note that this approach has very different performance characteristics, but is actually very useful in many situations when you are not looping over strings.
See String Append, Adding Strings Together.
In this example, we saw how you can improve the syntax of your StringBuilder code. Use this syntax to chain your StringBuilders in cases where you call Append multiple times. It retains the enormous performance advantage of StringBuilder, and approximates the simple syntax of regular strings: the best of both worlds.