Add a newline in C#
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.
|
1 2 3 4 5 6 7 8 9 |
using System; public class Example { public static void Main() { Console.Write("First line\r\nSecond line"); } } |
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,
|
1 2 3 4 5 6 7 8 9 10 |
using System; public class Example { public static void Main() { Console.WriteLine("First line"); Console.WriteLine("Second line"); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { Console.Out.NewLine = "\r\n\r\n"; Console.WriteLine("First line"); Console.WriteLine("Second line"); } } |
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:
|
1 2 3 4 5 6 7 8 9 |
using System; public class Example { public static void Main() { Console.WriteLine($"First line{Environment.NewLine}Second line"); } } |
Output:
First line
Second line
That’s all about adding a new line in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)