TheDeveloperBlog.com


C# StringBuilder AppendLine Method

AppendLine adds strings with a newline. Here we take a closer look at the StringBuilder AppendLine method. With AppendLine, a newline sequence is automatically inserted after the argument is added to the StringBuilder buffer.


Example. AppendLine is called with zero arguments or one argument. When you call AppendLine with no arguments, it just appends the newline sequence and nothing else. With a string argument, it appends that string and also the newline sequence.

Note: There is currently no way to directly use a format string with AppendLine.

AppendFormat
C# program that uses AppendLine

using System;
using System.Text;

class Program
{
    static void Main()
    {
	// Use AppendLine.
	StringBuilder builder = new StringBuilder();
	builder.AppendLine("One");
	builder.AppendLine();
	builder.AppendLine("Two").AppendLine("Three");

	// Display.
	Console.Write(builder);

	// AppendLine uses \r\n sequences.
	Console.WriteLine(builder.ToString().Contains("\r\n"));
    }
}

Output

One

Two
Three
True

The newline sequence used in AppendLine is equal to "\r\n" which is also available by referencing Environment.NewLine. The program demonstrates this by using Contains("\r\n") which returns true.

Environment.NewLineContains

Discussion. There are two common ways to specify newlines: the character "\n" alone, and the sequence "\r\n". AppendLine always uses the sequence "\r\n". To save bytes from the output string, you can manually use "\n".

Tip: This means every line in your text output will be one character shorter. In ASCII format, this will save one byte per line.

And: Your C# program will actually save two bytes per line in its memory, because a character is two bytes long.

CharASCII Strings

Summary. We looked at the AppendLine method and its overloads on the StringBuilder type. We demonstrated the newline sequence used. We also revealed an interesting optimization strategy for saving memory and file size in some cases.