C# Escape Sequences: Representing Special Characters in Strings
Learn how to use escape sequences in C# to represent special characters (newline, tab, backslash, etc.) within strings. This tutorial explains common escape sequences, demonstrates their usage, and shows how to use verbatim strings (`@`) for handling strings with many backslashes, improving code readability and simplifying string manipulation.
Escape Sequences in C#
Escape sequences in C# are special character combinations that represent characters that are difficult to type directly or have a special meaning within the language. They begin with a backslash (`\`).
Common Escape Sequences
| Escape Sequence | Description | 
|---|---|
| \n | Newline (line break) | 
| \t | Horizontal tab | 
| \r | Carriage return | 
| \b | Backspace | 
| \a | Bell (makes a sound) | 
| \f | Form feed | 
| \v | Vertical tab | 
| \' | Single quote | 
| \" | Double quote | 
| \xhh | Unicode character (hexadecimal `hh`) | 
| \uhhhh | Unicode character (hexadecimal `hhhh`) | 
| \Uhhhhhhhh | Unicode character (hexadecimal `hhhhhhhh`) | 
Examples
Newline (`\n`)
Console.WriteLine("Line 1\nLine 2");
Tab (`\t`)
Console.WriteLine("Name\tAge");
Console.WriteLine("Alice\t30");
Unicode Character (`\xhh`, `\uhhhh`, `\Uhhhhhhhh`)
Console.WriteLine("\u20AC"); // Euro symbol (€)
Verbatim String Literals (`@`)
Verbatim strings, created using the `@` symbol before the string literal, treat backslashes as literal characters. This is useful for file paths and other strings containing many backslashes.
string filePath = @"C:\MyFolder\myfile.txt";
Note: Verbatim strings must be enclosed in double quotes (`""`). To include a double quote *within* a verbatim string, use two double quotes in a row (`""`).