C# Escape Sequences
Escape sequences are used to represent certain characters within a string, which would otherwise not be possible to include. In C#, escape sequences start with a back slash (\), which is then followed by one or more characters.
As previously discussed, a message can be written out to the console using the ‘WriteLine’ method.
Console.WriteLine("This is a string");
This writes out the message, ‘This is a string’, to the console. As can be seen in the above code, the message is contained in double quotes. In order to get a double quote to actually appear in the message within the console, an escape sequence needs to be used.
Console.WriteLine("This is a string containing \"double quotes\".");
Here, a back slash is placed before the double quote in order to get it to appear in the message.
This is a string containing "double quotes".
As well as using an escape sequence for printable characters, such as double quotes, they can also be used for non-printable characters, such as including a new line within a string.
Console.WriteLine("This is a string containing\na new line.");
The escape sequence ‘\n’ is used within this message to force part of it to appear on a new line.
This is a string containing a new line.
Below is a table containing some of the escape sequences that are available in C#.
Escape Sequence |
Description |
---|---|
\a | Bell (alert) |
\b | Backspace |
\f | Formfeed |
\n | New line |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\’ | Single quotation mark |
\” | Double quotation mark |
\\ | Back slash |
\? | Literal question mark |