CodeBlanks Logo Icon CodeBlanks

Verbatim strings

C# course · Beginner · Lesson 34/116

Learn to write raw text without escape sequences using @.

Verbatim strings

Writing a file path with many backslashes is tiring: "C:\\Folder\\File.txt". A verbatim string solves this with the @ prefix: @"C:\Folder\File.txt".

In verbatim mode the backslash counts as an ordinary character; it is not interpreted as an escape. To put a double quote inside, write it twice: @"""Hello""". It improves readability for long text.

Multi-line verbatim

A verbatim string preserves line breaks as they are. A definition like the one below yields a three-line text:

string poem = @"First line
Second line
Third line";
(here an actual line break replaces <br>).

It is ideal for embedding long text such as HTML or SQL in code. Combined with interpolation, $@"..." merges both powers.

Exercise Write a verbatim file path

Declare a path variable as a verbatim string with the value C:\Docs\Notes.txt. You must use the @ prefix. Then print path with Console.WriteLine.

Show example solution
\Docs\Notes.txt"; and print it with Console.WriteLine(path);
Example solution:
using System;

class Program
{
    static void Main()
    {
        string path = @"C:\Docs\Notes.txt";
        Console.WriteLine(path);
    }
}

Test yourself

  1. Write the verbatim prefix

    string path = ____"C:\Folder\File.txt";
    Show answer
    string path = @"C:\Folder\File.txt";
  2. Match each literal to its value

    @"x\y"
    x backslash y
    "x\ny"
    x newline y
    @"""q"""
    q inside quotes
    "x"
    just x
  3. Which is the most readable form for a file path?

    string path = ...;
    • string path = "C:\\Folder\\File.txt";
    • string path = "C:/Folder/File.txt";
    • string path = @"C:\Folder\File.txt";
    • string path = $"C:\\Folder\\File.txt";
    Show answer

    string path = @"C:\Folder\File.txt"; — Correct. The @ prefix takes backslashes as they are; this is the most readable.

All lessons in Beginner