Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 182 · Strings

Raw, Verbatim and UTF-8 String Literals

Learn C# string literal forms - escape sequences, verbatim @ strings, raw string literals with triple quotes and interpolation, indentation rules, multi-line text and u8 UTF-8 literals.

Most text in a program is short and simple, but some text fights back: Windows paths full of backslashes, JSON with quotes everywhere, regular expressions, SQL, HTML, multi-line messages. If you write those with ordinary escape sequences you end up with a thicket of \\ and \" that is hard to read and easy to break. C# has three better tools for it: verbatim strings (@"..."), raw string literals ("""...""", C# 11) and UTF-8 literals ("..."u8, C# 11) for byte data.

This lesson shows each form, when to pick which, and the rules that decide what whitespace ends up in your string.

Regular strings and escape sequences

A normal string literal uses backslash escapes for characters that cannot be typed directly.

Escape Meaning
\n, \r, \t new line, carriage return, tab
\", \', \\ quote, apostrophe, backslash
\0 the null character
\uXXXX UTF-16 code unit given as four hex digits
\UXXXXXXXX a full code point given as eight hex digits
\xH..\xHHHH variable-length hex (error-prone; avoid)
\e the escape character U+001B (C# 13)
C# Escape sequences

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Before C# 13 you had to write \u001b or \x1b for the terminal escape character, and \x1b[31m was a trap: \x takes up to four hex digits, so \x1b3 would swallow the 3. The dedicated \e avoids that problem. Prefer \u with exactly four digits over \x.

Verbatim strings with @

Prefix a string with @ and backslashes lose their special meaning. Everything is taken literally, including line breaks. The only escape left is a doubled quote "" for a quote character.

C# Verbatim strings

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Verbatim strings are great for paths and short multi-line text, but they have two drawbacks. The quote still needs doubling, which makes JSON and HTML ugly, and line endings are copied from your source file. If the file was saved with Windows line endings (\r\n) the string contains them, even when it runs on Linux; with Unix endings it contains \n. That can make tests and comparisons behave differently between machines. If it matters, normalize with Replace("\r\n", "\n"), or use raw strings, which have defined rules.

In an interpolated verbatim string, braces are still special: write {{ and }} for literal braces.

Raw string literals

A raw string literal starts and ends with at least three double quotes. Inside, nothing is an escape: quotes, backslashes and braces are all plain characters. It was added in C# 11 (.NET 7) and is the best choice for JSON, XML, regular expressions, SQL and embedded code.

C# A raw string literal

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look closely at the output: the backslashes in C:\temp\new and \"hi\" are printed exactly as typed, because the literal does not process escapes. Also notice that the output starts at the left margin although the source is indented. That comes from the whitespace rules below.

The rules for multi-line raw strings

For a raw string that spans several lines:

  1. The opening """ must be followed by a newline, and the closing """ must be on a line of its own.
  2. The text between them is the content. The first and last newline are not part of it.
  3. The whitespace in front of the closing """ defines the indentation to remove. That exact prefix is stripped from every line.
  4. Every non-blank content line must start with that same whitespace prefix. Otherwise the compiler reports an error.

So moving the closing quotes to the left keeps more indentation in the string; moving them right is an error unless all lines are indented at least as far.

C# Closing quotes control indentation

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first literal strips four spaces, because the closing quotes are indented four spaces. In the second, they are indented only two, so every line keeps two extra spaces. Run it and look at the dots to see exactly what remains.

What if a line is indented less than the closing quotes? The compiler refuses to guess:

C# Wrong indentation (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You will see an error like error CS8999: Line does not start with the same whitespace as the closing line of the raw string literal. Fix it by indenting the line or by moving the closing quotes left.

Quotes inside raw strings

What if your text contains three double quotes in a row? Use more quotes for the delimiters than the longest run inside. The delimiter can be any length of three or more.

C# Longer delimiters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A single-line raw literal ("""text""") is allowed too, and then the content cannot start or end with a quote character unless you use longer delimiters.

Interpolated raw strings

Put $ in front of a raw string and holes work again. The number of $ characters sets how many braces open a hole: with $, one brace is a hole; with $$, you need two braces ({{value}}) and a single brace is plain text. That is perfect for JSON, where braces are everywhere.

C# Raw strings with interpolation

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choose the number of $ signs so that the brace runs in your literal text are shorter than the hole delimiter. With $$ a double brace in the text such as {{ would be ambiguous, which is when you use $$$. All format and alignment specifiers work inside holes as usual: {{price:F2}}.

Rule of thumb: use a raw string for anything with quotes, braces or backslashes, and for any text that spans lines and should look good in your source. Keep a plain "..." for short text and a verbatim @"..." for paths if you like it.

Multi-line text and line endings

Raw strings preserve the line breaks exactly as they appear in the source file; the same line-ending caveat applies as for verbatim strings. If your tests compare multi-line output, normalize first, or build the text with string.Join(Environment.NewLine, lines) and \n, which you control. When you split a block of text into lines, ReadOnlySpan<char>.EnumerateLines() or StringReader.ReadLine() handle \n, \r\n and \r alike.

C# Processing multi-line text

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

UTF-8 string literals

.NET strings are UTF-16, but files, network protocols and JSON are almost always UTF-8. Converting every time with Encoding.UTF8.GetBytes("...") allocates a new array on each call. A UTF-8 literal has the suffix u8 and is encoded by the compiler at build time, directly into the program's data section. Its type is ReadOnlySpan<byte>, so it costs no allocation at run time (C# 11).

C# u8 literals

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The result is a span, which means you cannot store it in a normal field or use it across an await; call .ToArray() when you need a durable array, or declare a static ReadOnlySpan<byte> Name => "..."u8; property, which the compiler turns into a read-only data reference with no allocation. Interpolated u8 strings are not supported because the content must be known at compile time. The next lesson, Unicode, Rune and Encoding, explains why UTF-8 byte counts differ from Length.

Choosing a literal form

Situation Best choice
Short ordinary text "..."
Windows path, single-line @"C:\dir\file" (or a raw string)
JSON, XML, HTML, regex, SQL """...""" raw
Template with many braces $$"""..."""
Constant bytes for I/O "..."u8
Text with control characters "..." with escapes

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. In a verbatim string, how do you write a double quote character?

    Verbatim strings treat backslash literally, so a quote is written as two quote characters in a row.
  2. 2. What decides how much leading whitespace is removed from the lines of a multi-line raw string?

    The whitespace before the closing delimiter is the prefix removed from every line. A line that does not start with it causes a compile error.
  3. 3. You want to build JSON with interpolation, and the JSON contains single braces. What helps most?

    With $$ a hole is written {{x}}, and single braces are plain text. Backslash escapes do not exist in raw strings.
  4. 4. What type does the literal "abc"u8 have?

    A u8 literal is a ReadOnlySpan<byte> over data embedded in the assembly, so it needs no allocation.
  5. 5. Which statement about line endings in verbatim and raw strings is true?

    A multi-line literal contains whatever line endings your source file uses, so normalize them if you compare text across machines.

Summary

  • Regular literals use backslash escapes; \e (C# 13) is the terminal escape character, and \u with four digits beats \x.
  • Verbatim strings (@"...") take backslashes literally; a quote is written "".
  • Raw strings ("""...""", C# 11) have no escapes at all; the closing delimiter's indentation is removed from every line, and longer delimiters let the text contain """.
  • $$""" and $$$""" change how many braces mark a hole, ideal for JSON and CSS.
  • "text"u8 yields a ReadOnlySpan<byte> with no run-time allocation.
  • Multi-line literals keep the source file's line endings; normalize when comparing.

Next: Unicode, Rune and Encoding