How to escape the character \ in C#?
Asked
Active
Viewed 1e+01k times
7 Answers
59
You just need to escape it:
char c = '\\';
Or you could use the Unicode escape sequence:
char c = '\u005c';
See my article on strings for all the various escape sequences available in string/character literals.
Jon Skeet
- 1,335,956
- 823
- 8,931
- 9,049
12
You can escape a backslash using a backslash.
//String
string backslash = "\\";
//Character
char backslash = '\\';
or
You can use the string literal.
string backslash = @"\";
char backslash = @"\"[0];
Dustin Kingen
- 19,915
- 7
- 49
- 92
-
1He didn't say he wanted it as a char, he said he wanted to know how to write it. – Dustin Kingen Apr 01 '13 at 17:17
-
@Romoku: Well, the question talks about char rather than string, *and* uses single quotes in the example. I agree it could be clearer though. – Jon Skeet Apr 01 '13 at 17:18
-
1@JonSkeet Well I edited in the char to provide a complete answer. – Dustin Kingen Apr 01 '13 at 17:19
-
@Romoku: You might want to get rid of the `@'\'` bit as it's invalid. I had a brain-fart when I included it. Also, the `@` makes it a *verbatim* string literal, as opposed to a *plain* string literal without - both are string literals. – Jon Skeet Apr 01 '13 at 17:20
-
@JonSkeet I figured `@"\"[0]` was close enough. Probably not very efficient. – Dustin Kingen Apr 01 '13 at 17:25
1
If you want to output it in a string, you can write "\\" or as a character, you can write '\\'.
Umar Farooq Khawaja
- 3,845
- 1
- 29
- 51
1
Double escape it. Escape escape = no escape! \\
Joshua Grosso Reinstate CMs
- 2,026
- 2
- 14
- 31
Justin
- 6,133
- 9
- 45
- 69
1
Escape it: "\\"
or use the verbatim syntax: @"\"
Dave Clausen
- 1,247
- 1
- 12
- 22
-
The `@` is for verbatim, not global escape. Verbatim strings contain even the newline characters, etc. – Umar Farooq Khawaja Apr 01 '13 at 17:19
1
To insert a backslash you need to type it twice:
string myPath = "C:\\Users\\YourUser\\Desktop\\YourFile.txt";
The string myPath should now contain: C:\Users\YourUser\Desktop\YourFile.txt
TheProgrammer
- 58
- 10