5.2. Strings and Escape Sequences

You've already seen how a string variable can be assigned a literal value, as in

string name = "Katie";

However, sometimes certain string literals can pose problems. For example, suppose you want to display the following message:

John said: "Reach for the sky!"

If you try to write this as a normal string literal

string message = "John said: "Reach for the sky!"";

Visual Studio gets all confused because the double quotation marks are used to delimit the start and end of a string literal, not as part of the string itself.

To solve this problem, C# uses a special escape character within the string to signify that what follows is to be treated differently. The special escape character is the backslash character (\). In essence, the escape character says to treat whatever follows it as though it were part of the string literal itself. For example, suppose you rewrite the string literal like this:

string message = "John said: \"Reach for the sky!\"";

The double quotation mark before the word Reach and the double quotation mark at the end of the sentence are now treated as part of an escape sequence and, therefore, are printed out as part of the string literal. The end result is that the statement displays this:

John said: "Reach for the sky!"

Table 5-5 presents a list of the special escape sequences.

Table 5-5. Table 5-5
Escape SequenceInterpretation
\"Display a double quotation mark.
\'Display a single quotation mark.
\\Display a backslash.
\0Null (non-printing). ...

Get Beginning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.