TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# StringBuilder AppendLine Method

This C# example program tests the 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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf