C#: Escape Double-quote within a String


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.


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 "example", and may include both simple escape sequences (such as \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.


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.


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.";
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: