I need to use " and ' as a character in C#, however they are special characters. So when I put them as character in the string, it will give an error. The issue is that it has many " and ' so I need to find a way to allow me to use these special characters. How can I do that
Asked
Active
Viewed 724 times
0
-
5You might find what you're looking for by using the words "escape" in google or even just the stack overflow search. Try: "C# escaping" – Chris Pfohl Nov 19 '13 at 21:40
-
See this question: How to add doublequotes to a string that is inside a variable? - http://stackoverflow.com/questions/3905946/how-to-add-doublequotes-to-a-string-that-is-inside-a-variable – Stainy Nov 19 '13 at 21:42
-
use an [at] like this: var mystring = @"my string includes a " character!" OR escape it with a backslash: var mystring = "my string contains a \" character!" – sjkm Nov 19 '13 at 21:44
5 Answers
7
Use escape sequences: "This is a double-quote: \", and this is a single quote: \'"
Although note that since the string is delimited by double quotes, the \'
escape isn't necessary: "This is a double-quote: \", and this is a single quote: '"

alecbz
- 6,292
- 4
- 30
- 50
-
2A single quote doesn't need to be escaped, unless you're trying to get the single quote `char`: `'\''` – Tim S. Nov 19 '13 at 21:42
3
Simple prefix your string with @
for "
use ""
This makes newlines easy as pie:
string example = @"A string that has double quote "" and single quote ' also a new line
";

Hogan
- 69,564
- 10
- 76
- 117
1
Having a single quote '
in string doesn't trouble C#, its the double quotes "
, you have to escape them with backslash like:
string str = "some\"stri'''''ng";
You can also use verbatim string @
in the start and then you have to escape double quotes with another double quote like:
string str = @"some""stri'ng";

Habib
- 219,104
- 29
- 407
- 436
0
Put a backslash before special chars you want to use to escape them.
Here's a list:

Plasmarob
- 1,321
- 12
- 20