Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

blackslash
c#
print

How to print a backslash \ in C#

Theodore Kelechukwu Onyejiaku

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("\");
    }
}
Printing a backslash in C# throws an error

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!");
    }
}
Printing out a double backslash prints a single blackslash

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.

RELATED TAGS

blackslash
c#
print

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring