Sometimes, you want to store quotation marks within a string, as in the following example
"Alive", she cried!
In C#, there are at least 4 ways to embed a quote within a string:
- Escape quote with a backslash
- Precede string with @ and use double quotes
- Use the corresponding ASCII character
- Use the Hexadecimal Unicode character
Escape with backslash
You can precede any escaped character with a backslash ("\") to preserve that character.
For example:
var lyrics = "\"Alive\", she cried!"
Precede with @ and use double quotes
If you precede the string with the "@" character, you can use a double set of quotation marks to indicate a single set of quotation marks within a string.
For example:
var lyrics = @"""Alive"", she cried!"
Use the ASCII character
A double quote is the ASCII value 34, so you can append this to your string.
For example:
quote = (char)34 + "Alive" + (char)34 + ", she cried!";
Use the Hexadecimal Unicode character
You can escape Unicode characters by preceding the hexadecimal value with "\u". The hexadecimal value of a double quote is 0022, so you can include this in your string.
For example:
quote = "\u0022Alive\u0022, she cried!";
These techniques work for many other characters that are difficult to represent within quotation marks, such as line feeds, non-English characters, and non-printing characters.
There are other ways to include quotation marks within a C# string, but these should be enough to get you started.