What is a verbatim string literal and why do we use it?
Short answer
A verbatim string literal in C# is created by placing an at symbol directly before the opening quotation mark, and it tells the compiler to treat the string exactly as written, ignoring normal escape sequences like backslash n for a new line.
Advertisement
AModel answer
A verbatim string literal in C# is created by placing an at symbol directly before the opening quotation mark, and it tells the compiler to treat the string exactly as written, ignoring normal escape sequences like backslash n for a new line. Verbatim strings are especially useful for file paths, regular expressions, and multi line text, since they let you write backslashes and line breaks directly without needing to escape every special character.
string path1 = "C:\\Users\\Test\\file.txt";
string path2 = @"C:\Users\Test\file.txt";
// Both represent the same file pathReal-world example
A developer writing a file processing utility uses a verbatim string literal to store a Windows file path, avoiding the need to escape every single backslash character in the path manually.
Likely follow-ups
- Can a verbatim string literal span multiple lines?
- How do you include an actual quotation mark inside a verbatim string?
Related topics