C# Escape Sequences (Characters)

In C#, escape characters are special characters that allow you to include non-printable characters in strings. Escape characters are used to represent characters that cannot be typed directly into a string, such as tabs, newlines, and quotes.

Common Escape Characters in C#

Here are some common escape characters used in C#:

Escape CharacterDescription
\\Backslash
\'Single quote
\"Double quote
\nNewline
\rCarriage return
\tTab
\bBackspace
\fBackspace

Examples

Here are some examples of how to use escape characters in C#:

1// Backslash 2string path = "C:\\My Documents\\File.txt"; 3 4// Single quote 5string message = "Don't forget to save your work."; 6 7// Double quote 8string quote = "\"To be or not to be,\" said Hamlet."; 9 10// Newline 11string address = "123 Main Street\nAnytown, USA 123"; 12 13// Carriage return and newline 14string message = "Hello,\r\nHow are you?"; 15 16// Tab 17string message = "Name:\tWilliam\tMax\nAge:\t24"; 18 19// Backspace 20string message = "abc\bde";

In the first example, the backslashes are used to escape the backslashes in the file path. Without the escape characters, the string would be interpreted as "C:My DocumentsFile.txt".

In the second example, the single quote is escaped with a backslash so that it can be included in the string.

In the third example, the double quotes are escaped with a backslash so that they can be included in the string.

In the fourth example, the \n escape character is used to insert a newline into the string.

In the fifth example, the \r and \n escape characters are used to insert a carriage return and a newline into the string.

In the sixth example, the \t escape character is used to insert a tab into the string.

In the seventh example, the \b escape character is used to insert a backspace into the string.