This post will discuss how to add a newline (line break) in C#.

A newline marks the end of the current line and the start of a new one. Unix/Mac/Windows machines have different notations for representing a newline. It is typically done using one or two escape characters. For example, the newline is represented by a single line feed (LF) character ("\n") on Unix/Linux operating systems; while on Microsoft Windows, a newline is represented by a carriage return followed by a line feed ("\r\n"). The classic Mac operating system uses a single carriage return (CR) character for line breaks, represented as "\r".

1. Platform-dependent solution

Depending upon your environment, you can use platform-dependent newline characters. For instance, "\n" for Unix, "\r\n" for Windows, and "\r" for Mac. For example, the following program outputs two lines separated by a CR-LF character. The problem with this approach is that your code will not be portable.

Download  Run Code

Output:

First line
Second line

2. Using Console.WriteLine() method

The commonly used solution is to make use of the Console.WriteLine() method, which automatically appends a line terminator character to the standard output stream. In C#, the default line terminator is "\r\n" (carriage return followed by a line feed). For example,

Download  Run Code

Output:

First line
Second line

 
It is worth noting that you can change the default line terminator by modifying the value of the TextWriter.NewLine property of the Out property. The following code illustrates this:

Download  Run Code

Output:

First line

Second line

3. Using Environment.NewLine Property

The recommended approach is to use the Environment.NewLine property, which is the newline string constant defined for the current platform. It typically returns "\r\n" for non-Unix platforms, or "\n" for Unix platforms. The following program demonstrates the usage of the Environment.NewLine property:

Download  Run Code

Output:

First line
Second line

That’s all about adding a new line in C#.