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 errorConsole.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 backslashConsole.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.