When working with strings of text, there are certain characters that you can’t represent in a normal string variable because the key required on the keyboard simply doesn’t exist or because of how strings are represented in text. Fortunately, modern programming languages provide “escape sequences,” or ways to represent certain characters that otherwise could not be represented, in a string.
Let’s say we wanted to represent the following string of text in a string:
“Hello, How are you doing today?”, I asked.
With a string, traditionally you would surround the line of text with quotes, resulting in:
“”Hello, How are you doing today?”, I asked.”
However, the above will result in a syntax error because as far as a programming language is concerned, the first double quote is representitive of the beginning of a string and the second double quote is representitive of the end of the string. The language would thing the string is over immediately after the double quotes.
Fortunately, we can represent the string like this and get the result we were looking for:
“\”Hello, How are you doing today?\”, I asked.”
In C# and Visual Basic, using the backslash character indicates that the very next character will be an escape sequence. For example placing “\n” in a string would not represent a backslash and then the ‘n’ character, but rather a new line. To make use of a backslash, once again, you use an escape sequence. Use the “\\” to make a backslash.
Here’s a full set of escape sequences in C# and Visual Basic:
\'– Single quote, needed for character literals
\"– Double quote, needed for string literals
\0– Unicode character 0
\a– Alert (character 7)
\b– Backspace (character 8 )
\f– Form feed (character 12)
\n– New line (character 10)
\r– Carriage return (character 13)
\t– Horizontal tab (character 9)
\v– Vertical quote (character 11)
\uxxxx– Unicode escape sequence for character with hex value xxxx
\xn[n][n][n]– Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
\Uxxxxxxxx– Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)