How to print a new line in C#

Overview

There are three ways to print a new line:

  • Console.WriteLine(): This prints a new line. If any message, text, or value is printed with this method, a new line will be printed after it.

  • \n: This is an escape character. With this added to the Console.WriteLine() or Console.Write() method, a new line will be printed to the console.

  • \x0A or \xA: These are the ASCII literals of the escape character, \n. When used, they produce a new line.

Example

using System;
class HelloWorld
{
static void Main()
{
//when \n is used
Console.WriteLine("Hello\nWorld");
Console.Write("Hello\nWorld");
//when \x0A is used
Console.WriteLine("Hello\x0AWorld");
//when Console.WriteLine() is used
Console.WriteLine();
Console.WriteLine("end of the program");
}
}

Explanation

  • Lines 8 and 9: We use the \n escape character. We first use it on the Console.WriteLine() method and then on the Console.Write() method.

  • Line 12: We use the ASCII literal \x0A and print a text to the console.

  • Line 15: We use the Console.WriteLine() method to print a new line.

Free Resources