C# StringBuilder AppendLine

Letters of the alphabet: ABC

AppendLine adds strings with a newline. Here we take a closer look at the AppendLine method on the StringBuilder type in the C# language. With AppendLine, a newline sequence is automatically inserted after the arguments—if any—are added to the StringBuilder buffer.

This C# example program tests the StringBuilder AppendLine method.

Example

Note

The AppendLine method can be called with zero arguments or one argument. When you call AppendLine with no arguments, it just appends the newline sequence and nothing else. When you call AppendLine with a string argument, it append that string and also the newline sequence. There is currently no way to use a format string with AppendLine directly.

Program that uses AppendLine [C#]

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

Newline sequence. 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.NewLine

Optimization

Performance optimization

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". This means every line in your text output will be one character shorter. In ASCII format, this will save one byte per line. Your C# program will actually save two bytes per line in its memory, because a character is two bytes long.

Char ASCII String Representation

Summary

The C# programming language

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

StringBuilder Secrets
.NET