TheDeveloperBlog.com


C# StringBuilder Append

Append method calls can be chained. This makes your StringBuilder code more succinct and easier to read. Instead of using dozens of Append lines, we can have just one. And in some program contexts this is ideal.

StringBuilder Append Performance

Example. To start, we see how many developers use StringBuilder. Remember that StringBuilder often improves your application's performance, and is an important part of your tool belt as a developer.

In the second part, we 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.

Note: Excessive method calls, on separate lines, are ugly and verbose—and thus prone to errors.

C# program that uses Append syntax

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");
	}
    }
}

C# program that uses altenative Append syntax

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");
	}
    }
}


Concat. Another option when you want to Append strings together is to use the plus operator. Note that this approach has different performance characteristics, but is useful in many situations when you are not looping over strings.

String AppendConcat

Summary. We saw some StringBuilder code. You can use this syntax to chain your StringBuilders in cases where you call Append multiple times. It retains the enormous performance advantage of StringBuilder.

And: It approximates the simple syntax of regular strings. This yields the best of both worlds.