How to escape the character \ in C#?
7 Answers
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.
Comments
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];
5 Comments
Dustin Kingen
He didn't say he wanted it as a char, he said he wanted to know how to write it.
Jon Skeet
@Romoku: Well, the question talks about char rather than string, and uses single quotes in the example. I agree it could be clearer though.
Dustin Kingen
@JonSkeet Well I edited in the char to provide a complete answer.
Jon Skeet
@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.Dustin Kingen
@JonSkeet I figured
@"\"[0] was close enough. Probably not very efficient.Escape it: "\\"
or use the verbatim syntax: @"\"
1 Comment
Umar F Khawaja
The
@ is for verbatim, not global escape. Verbatim strings contain even the newline characters, etc.