Csharp Verbatim String
In this tutorial, you'll learn about C# Verbatim String. We cover key concepts, practical examples, and best practices.
A file path on Windows: "C:\\Users\\Alice\\Documents\\file.txt". Every backslash is doubled. A multi-line SQL query requires \n or concatenation. Verbatim strings @"..." treat backslashes as literal characters and span multiple lines.
Wrong
string path = "C:\\Users\\Alice\\Documents\\file.txt";
string sql = "SELECT *\nFROM Users\nWHERE Id = 1\nORDER BY Name";
Output: Works, but the path has doubled backslashes and the SQL is hard to read with \n.
Right
string path = @"C:\Users\Alice\Documents\file.txt";
string sql = @"SELECT *
FROM Users
WHERE Id = 1
ORDER BY Name";
Output: Same values. The path uses single backslashes. The SQL spans lines naturally.
Combining with string interpolation:
string name = "Alice";
string message = $@"Hello {name},
Your file is at: C:\Users\{name}\Documents\";
The @ prefix makes backslashes literal (no escaping), preserves newlines, and treats quotes as literal when doubled ("").
Prevention
- Use
@"..."for file paths, registry paths, and any string with backslashes. - Use
@"..."for multi-line strings like SQL, JSON, or XML. - Use
$@"..."for interpolated verbatim strings. - Use
""inside a verbatim string for a literal double quote:@"He said ""Hello"".". - Use raw string literals
"""..."""(C# 11) for strings with many quotes or complex embedded languages. - Do not use
@"..."for short single-line strings without backslashes — regular strings are simpler.
Common Mistakes with verbatim string
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Verbatim strings are used in DodaZIP for path handling across platforms. For more C# string tips, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro