Rewrite our StringBuilder-using code to be more succinct and easy to read. Instead of using dozens of Append calls in the traditional manner, we want to see how the C# designers made the StringBuilder class able to be used in a more compact and readable way. We want to retain our performance but also make the code shorter, balancing readability with speed.
Remember that StringBuilder often improves your application's performance, and is a very important of your tool belt as a developer--it can make an algorithm a thousand times faster. First, let's look at some sample StringBuilder code that uses the regular syntax. Note how it has three Append calls on separate lines.
private string Test1()
{
// Conventional StringBuilder syntax. Works well.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
builder.Append("One string ");
string testValue = SomeFunc(i);
builder.Append(testValue);
builder.Append("Another string");
}
return builder.ToString();
}
StringBuilder's Append method returns a reference to itself. This is because the designers of C# foresaw the problem with repetitive StringBuilder appends. They are ugly and repetitive, and thus prone to errors. The above code could be improved by chaining StringBuilder Append calls.
private string Test2()
{
// This is a fluent interface for StringBuilder. You can use dot
// notation to call Append on itself. Shorter code, faster to type,
// looks more elegant, and does the same thing.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
builder.Append("One string ").Append(SomeFunc(i)).Append("Another string");
}
return builder.ToString();
}
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. Call Append repeatedly on itself to get the best of both worlds.