What is an escape sequence? Well, put simply, an escape sequence is a series of special characters which are interpreted by the compiler as a command. In other words, they suspend the normal processing to perform some special function.
In C#, escape sequences are represented by a ‘\’ (backslash) followed by a letter or a combination of digits.
The following table represents the most common escape sequences used in C#.
|Escape Sequence||What it Represents|
|\’||Single Quotation Mark (character 39)|
|\”||Double Quotation Mark (character 34)|
|\?||Literal Question Mark|
|\\||Backslash (character 92)|
|\a||Alert/Bell (character 7)|
|\b||Backspace (character 8 )|
|\f||Formfeed (character 12)|
|\n||New Line (character 10)|
|\r||Carriage Return (character 13)|
|\t||Horizontal Tab (character 9)|
|\v||Vertical Tab (character 11)|
|\ooo||ASCII character in octal notation|
|\xhh||ASCII character in hexadecimal notation|
- In the below code we are escaping the backslash in the path string.
string path = "C:\\Program Files\\Microsoft";
The result would look like this: C:\Program Files\Microsoft
- In the below code we are adding a carriage return and a new line by using the \r\n escape sequences together.
MessageBox.Show("Hello from...\r\nhttp://www.daveoncsharp.com", "Escape Sequences", MessageBoxButtons.OK, MessageBoxIcon.Information);
The result will be a message box with the message string split on two lines as shown below.
I hope you found this useful. Feel free to visit this blog often for more similar articles.