skip to content

In C#, how do a verbatim string @"..." and a raw string literal """...""" differ for paths, quotes and multi-line JSON?

level: middleimportance: should knowfreq 40%

answer

  1. which escapes survive
  2. doubling the quote character
  3. where the closing delimiter sits
  4. indentation stripped or kept

basics

~20 s

A verbatim @"..." ignores backslash escapes, but a quote is written "" and source indentation stays in the text. A raw literal (C# 11) has no escapes at all, and its multi-line form strips the closing delimiter's indentation.

solid answer

~40 s

In `@"..."` a backslash is literal, so paths read naturally, but `\n` is not a newline either, a quote must be doubled as `""`, and multi-line content keeps all its source indentation. A raw string literal, added in C# 11, opens and closes with at least three quotes and has no escape sequences at all; if the content contains `"""`, you lengthen the delimiter. Its multi-line form puts the opening and closing quotes on their own lines and removes the whitespace to the left of the closing `"""` from every line, so a JSON fixture can be indented with the code and still start with `{`. The compiler enforces the layout: an under-indented line is CS8999 and a closing delimiter after content is CS9000.

code

csharp · 22 lines
csharp
string regular  = "C:\\exports\\invoices\\\"Q4\".json";
string verbatim = @"C:\exports\invoices\""Q4"".json";
string raw      = """C:\exports\invoices\"Q4".json""";
Console.WriteLine(regular == verbatim && verbatim == raw);

string expected = """
    {
      "invoiceId": "INV-1001",
      "note": "paid in \"full\""
    }
    """;
Console.WriteLine(expected);
Console.WriteLine(expected.StartsWith('{'));
Console.WriteLine(expected.EndsWith('}'));

string quotes = """"He wrote """ in the note."""";
Console.WriteLine(quotes);

string verbatimMulti = @"{
      ""invoiceId"": ""INV-1001""
    }";
Console.WriteLine(verbatimMulti);

go deeper

for a junior

Recall that @ makes backslashes literal and that a quote inside a verbatim string is doubled.

for a middle

Explain the raw literal rules: three or more quotes, no escapes, delimiters on their own lines, and indentation removed relative to the closing quotes.

for a senior

Show how raw literals make JSON, SQL and generated code fixtures reviewable, and read the CS8997, CS8999 and CS9000 errors without trial and error.

for a principal

Weigh converting existing verbatim fixtures to raw literals: clearer diffs and no doubled quotes against churn in files nobody else is touching.

"## Three ways to write a string literal C# has three literal forms that matter for everyday text, and each solves a different escaping problem: | Form | Example | Backslash | Double quote | Newlines in source | |---|---|---|---|---| | Regular | `"C:\\exports\\\"Q4\".json"` | escape character (`\\`, `\n`, `\"`) | `\"` | not allowed (CS1010) | | Verbatim | `@"C:\exports\""Q4"".json"` | literal character | doubled: `""` | kept as typed | | Raw (C# 11) | `"""C:\exports\"Q4".json"""` | literal character | literal character | allowed in the multi-line form | All three of those examples produce the same string. Raw literals arrived in C# 11, which is already part of the C# 12 baseline on .NET 8, and they compile to an ordinary `string`: nothing changes at run time. ## Verbatim strings A **verbatim string** starts with `@"`: - Backslashes are ordinary characters, which is why `@` became the habit for file paths with backslashes and for regular expressions. - Escape sequences are not processed at all: `@"Line\nNext"` contains a backslash and an `n`, not a newline (that example is 10 characters long). - The only escape left is the quote: write `""` to get one `"`. - Line breaks are kept, and so is **every space of source indentation** on the following lines. A verbatim JSON block indented to match the surrounding code carries that indentation into the string. ## Raw string literals A **raw string literal** starts and ends with at least three double quotes. Its content has no escapes of any kind. Two forms exist: 1. **Single-line**: `"""He said "paid" twice"""`. The content must sit on the same line as both delimiters. 2. **Multi-line**: the opening quotes end their line, the content follows on its own lines, and the closing quotes start their own line. If the content contains `"""`, use a longer delimiter: `""""He wrote """ in the note.""""`. The rule is that the content may not contain a run of quotes as long as the delimiter or longer. ## The indentation rule The multi-line form is what makes raw literals pleasant for embedded JSON or XML: - Whatever whitespace stands **to the left of the closing `"""`** is removed from the start of every content line. - The newline right after the opening delimiter and the newline right before the closing one are not part of the string. - So a JSON block indented four spaces in the source, with the closing quotes also indented four spaces, yields a string whose first character is `{`. - Every content line that is not blank must start with that exact whitespace (spaces and tabs are not interchangeable), or the compiler rejects it. ## What the compiler rejects These are the messages the .NET 10 SDK printed for the common mistakes: - A content line indented less than the closing delimiter: **CS8999**, "Line does not start with the same whitespace as the closing line of the raw string literal." - The closing quotes placed after content on the same line, as in `}"""`: **CS9000**, "Raw string literal delimiter must be on its own line." - Content written right after the opening quotes, as in `"""{`, followed by more lines: that makes it a single-line literal, and the line break ends it with **CS8997**, "Unterminated raw string literal.", followed by knock-on syntax errors. ## Which one to reach for - **Regular** strings for short text with the odd `\n` or `\t` you want interpreted. - **Verbatim** strings still read fine for a single-line file path or regex, and much existing code uses them. - **Raw** strings for anything with quotes or several lines: JSON fixtures, SQL, XML and generated code, where doubling every quote and fighting the indentation is where bugs creep in. They combine with `$` for interpolation, with an extra rule for braces.

  • How do you put three consecutive double quotes inside a raw string literal?
    Make the delimiter longer than any run of quotes in the content. `""""He wrote """ in the note.""""` opens and closes with four quotes, so the three in the middle are content. With a three-quote delimiter the inner `"""` would close the literal early and the rest fails to parse.
  • Why does a raw literal written as """{ with the JSON continuing on the next lines fail to compile?
    Content on the opening line makes it a single-line raw literal, and a single-line literal cannot contain a line break, so the SDK reports CS8997, "Unterminated raw string literal." Move `{` to the next line. The mirror mistake, `}"""` on the last content line, is CS9000, because the closing delimiter must be on its own line.
  • Does @"Line\nNext" contain a line break?
    No. A verbatim string processes no escape sequences except the doubled quote, so `\n` stays as two characters, a backslash and an `n`, and the string is 10 characters long. To get a real line break in a verbatim string you press Enter inside it, or switch to a regular or raw literal.

  • A verbatim string needs no escaping at all, quotes included.
  • In a verbatim string, \n still produces a newline.
  • A multi-line raw literal keeps the source indentation of every line.
  • Raw string literals need .NET 10, so .NET 8 projects cannot use them.
  • Mixing tabs and spaces in raw literal indentation is fine if it looks aligned.