What is Verbatim String in C#: Explanation and Examples
verbatim string in C# is a string literal prefixed with @ that preserves all whitespace and special characters exactly as typed, including new lines and backslashes. It allows writing strings without needing to escape backslashes or quotes, making it easier to write file paths or multi-line text.How It Works
Imagine writing a note where every space, line break, and symbol is exactly as you want it to appear. A verbatim string in C# works like that note. When you start a string with @, C# treats everything inside the quotes exactly as you type it, including new lines and backslashes.
Normally, in C#, you have to use special codes like \n for new lines or \\ for a backslash. But with a verbatim string, you don’t need to do that. It’s like telling the computer, "Take this text exactly as it is." This is very helpful when writing file paths or long text blocks where escaping characters would be confusing.
Example
This example shows a normal string versus a verbatim string for a Windows file path. Notice how the verbatim string is easier to read and write.
using System; class Program { static void Main() { string normalPath = "C:\\Users\\John\\Documents\\file.txt"; string verbatimPath = @"C:\Users\John\Documents\file.txt"; Console.WriteLine("Normal string: " + normalPath); Console.WriteLine("Verbatim string: " + verbatimPath); string multiLine = @"This is line one. This is line two. This is line three."; Console.WriteLine("\nMulti-line verbatim string:\n" + multiLine); } }
When to Use
Use verbatim strings when you want to write file paths, regular expressions, or any text that contains many backslashes or special characters. They are also great for writing multi-line text directly in your code without needing to add \n for new lines.
For example, if you are working with Windows file paths, using verbatim strings makes your code cleaner and easier to understand. Also, when you want to include a block of text exactly as it appears, verbatim strings save you time and reduce errors.
Key Points
- Verbatim strings start with
@"and end with". - They preserve all whitespace and new lines inside the string.
- Backslashes
\do not need to be escaped. - To include a double quote inside, write it twice:
"". - Useful for file paths, multi-line text, and complex strings.