How to print a backslash \ in C#

Overview

Printing a backslash in C# will print an error. This is because the backslash \ is a special character used for escape sequences like the new line \n, a tab \t, a space \s, etc. If we try to print the backslash, an error is thrown.

So how do we print this special character? To print it, we have to use a double slash \\.

Syntax

Console.WriteLine('\\')
Syntax to print a backslash

Return value

A single backslash is returned.

Code example

using System;
class HelloWorld
{
static void Main()
{
// printing a backslash throws an error
Console.WriteLine("\");
}
}

Explanation

  • In line 7 we print the backslash. And when the code is run, an error is thrown.

Code example

using System;
class HelloWorld
{
static void Main()
{
// print a backslash
Console.WriteLine("\\");
Console.WriteLine("This is new line \\n and tab \\t");
Console.WriteLine("Welcome\\to\\Edpresso!");
}
}

Explanation

  • In lines 7-9 we print the escape sequences together with some strings. This does not cause any error, because we was used backslash with escape sequence character.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources