String Escape Sequence

In C#, an escape sequence is a combination of characters that represents a special or non-printable character within a string. Escape sequences start with a backslash ('\') followed by one or more characters to convey a specific meaning. These sequences allow you to include characters in a string that may be difficult to represent directly.

Here are some common escape sequences used in C#:
  1. '\n': Newline - Represents a line break or a new line.
  2. '\r': Carriage return - Represents a return to the beginning of the line.
  3. '\t': Tab - Represents a horizontal tab.
  4. '\\': Backslash - Represents a literal backslash character.
  5. '\'': Single quote - Represents a single quote character.
  6. '\"': Double quote - Represents a double quote character.

Example:


string message = "Hello,\n\t\"C#\" World!";
Console.WriteLine(message);

Output:


Hello,
    "C#" World!

In the example above, the '\n' represents a newline, the '\t' represents a tab, and the '\"' represents a double quote character.

If you want to include a backslash '\' as a literal character in the string, you need to escape it with another backslash like '\\'.


string path = "C:\\Users\\John\\Documents\\file.txt";

Output:


C:\Users\John\Documents\file.txt

Using escape sequences, you can include special characters in strings that would otherwise be challenging to represent directly. This is especially useful when working with file paths, regular expressions, or strings that contain formatting instructions.