Problem
When you need to add a double-quote character to a string, you will run into a problem. Double-quotes are the delimiters for the beginning and end of a string, so placing a double-quote within a string will confuse the compiler and it will give you an exception.
Solution
There are two solutions for escaping double-quote (quote-escape-sequence) characters within a string, and the one you use depends on what type of string literal you are using: regular string literal, or verbatim string literal.
Regular String Literal
These types of strings are strings that consist of zero or more characters enclosed in double quotes, as in "
, and may include both simple escape sequences (such as example
"\t
for the tab character) and hexadecimal and Unicode escape sequences.
To escape a double-qoute within a regular string literal, all you need to do is use the backslash character (\) in front of the double-quote.
Examples
string myRegularString = "Here's a double-quote character: \""; string myRegularString2 = "Yet another \" for you.";
Verbatim String Literal
These types of strings consist of an @
character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is@"example"
. The characters between the delimiters are interpreted verbatim (meaning “as is”), the only exception being a quote-escape-sequence. Simple escape sequences (such as \t
for the tab character) and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.
Examples
string verbatimString1 = @"Here's a verbatim string with a double-quote character: """; string verbatimString2 = @"And another "" for you."; string verbatimString3 = @"String that spans multiple lines and includes the "" character in it.";