Raw string literals and UTF-8 string literals

suggest change

C# 11 added two new kinds of string literals:

C# 13 also added the \e escape sequence for the ESC character. It's covered at the end.

Regular "..." literals are covered in string literals, @"..." in Verbatim String and $"..." in String Interpolation.

The examples are C# 14 / .NET 10 file-based programs: save the code as app.cs and run dotnet run app.cs.

Why raw strings

Here is the same JSON text written three ways:

string regular  = "{\"name\": \"Ann\", \"path\": \"C:\\temp\"}";
string verbatim = @"{""name"": ""Ann"", ""path"": ""C:\temp""}";
string raw      = """{"name": "Ann", "path": "C:\temp"}""";

Console.WriteLine(regular);
Console.WriteLine(verbatim);
Console.WriteLine(raw);
Console.WriteLine(regular == verbatim && verbatim == raw);
{"name": "Ann", "path": "C:\temp"}
{"name": "Ann", "path": "C:\temp"}
{"name": "Ann", "path": "C:\temp"}
True

A regular string needs \" for quotes and \\ for backslashes. A verbatim string keeps backslashes as they are but still needs "" for every quote. The raw string contains exactly the text you want, so you can copy JSON, XML, SQL or a regex from another tool and paste it in unchanged.

Multi-line raw strings

A multi-line raw string has the opening """ at the end of one line and the closing """ on a line of its own:

string xml = """
    <person>
      <name>Ann</name>
      <tags>"admin" "dev"</tags>
    </person>
    """;

Console.WriteLine(xml);
Console.WriteLine($"starts with '<': {xml[0] == '<'}");
Console.WriteLine($"ends with newline: {xml.EndsWith('\n')}");
<person>
  <name>Ann</name>
  <tags>"admin" "dev"</tags>
</person>
starts with '<': True
ends with newline: False

The rules are:

The last rule decides how much indentation you keep:

void Show(string s) => Console.WriteLine("[" + s.Replace("\n", "\\n") + "]");

// closing """ indented by 4: 4 spaces removed from every line
Show("""
    a
      b
    """);

// closing """ indented by 2: the extra 2 spaces of every line are kept
Show("""
      a
        b
    """);

// blank lines don't need the indentation
Show("""
    first

    third
    """);

// an empty last line gives a trailing newline
Show("""
    line

    """);
[a\n  b]
[  a\n    b]
[first\n\nthird]
[line\n]

In the second call the closing quotes are indented by 4 spaces and the content by 6, so each line keeps 2 spaces. Relative indentation inside the text (like b under a) is always preserved.

Compile errors you will see

The compiler is strict about the layout. Each of these fails:

// CS8999: Line does not start with the same whitespace as the closing line
string a = """
    one
  two
    """;

// CS9000: Raw string literal delimiter must be on its own line
string c = """
    text""";

// CS8997: Unterminated raw string literal
// (text after the opening """ makes it a single-line raw string,
//  which must end on the same line)
string b = """first line
    more
    """;

// CS8997: """""" is not an empty string, it's an unterminated 6-quote literal
string d = """""";

Every content line must start with the exact whitespace of the closing line. Mixing tabs and spaces counts as a mismatch. Use "" or string.Empty for an empty string.

Quotes inside raw strings

A raw string can contain any run of quotes shorter than its delimiter. If the text contains """, start and end the literal with four quotes. If it contains """", use five, and so on:

string a = """She said "hi" and "bye".""";
string b = """"A raw string starts with """ and ends with """."""";
string c = """"
    In C# 11 you can write:
        string s = """
            Hello
            """;
    """";

Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
She said "hi" and "bye".
A raw string starts with """ and ends with """.
In C# 11 you can write:
    string s = """
        Hello
        """;

A single-line raw string can't start or end with a quote character, because that quote would merge with the delimiter. """"say "hi""""" fails with CS8998 ("does not start with enough quote characters"). Use the multi-line form instead, where the delimiters are on their own lines:

using System.Text.RegularExpressions;

var quoted = new Regex("""
    (\w+)="([^"]*)"
    """);
foreach (Match m in quoted.Matches("""id="42" class="big red" x=1"""))
    Console.WriteLine($"{m.Groups[1].Value} -> {m.Groups[2].Value}");
id -> 42
class -> big red

This is also a good example of raw strings for regular expressions: \w is written as \w, not \\w, and the " in the pattern needs no escaping.

Interpolated raw strings

Put $ before a raw string to interpolate it. With one $, { and } work as in a normal $"..." string, including alignment and format specifiers:

string name = "Ann";
int age = 41;
double score = 0.8765;

// one $: { } are interpolation holes, just like $"..."
string text = $"""
    Name:  "{name}"
    Age:   {age,5}
    Score: {score:P1}
    """;
Console.WriteLine(text);

// two $$: {{ }} are holes, single { } are literal text
string json = $$"""
    {
      "name": "{{name}}",
      "age": {{age}},
      "tags": ["a", "b"],
      "nested": { "ok": {{(age > 18 ? "true" : "false")}} }
    }
    """;
Console.WriteLine(json);
Name:  "Ann"
Age:      41
Score: 87.6%
{
  "name": "Ann",
  "age": 41,
  "tags": ["a", "b"],
  "nested": { "ok": true }
}

(The P1 output depends on the current culture; this is en-US.)

In a regular $"..." string, a literal brace has to be doubled ({{). Raw strings work the other way around: the number of $ signs is the number of braces that open and close a hole. With $$, {{expr}} is a hole and a single { or } is plain text, which is what JSON, CSS and C-like code need.

The rule for longer runs of braces: in a $$ string, a run of up to 2 braces next to a hole is fine. The innermost 2 belong to the hole and any extra brace is literal text:

string prop = "color";
string value = "red";

// $$: {{x}} is a hole; {{{x}}} is a literal { followed by a hole and a literal }
string css = $$""".box { {{prop}}: {{value}}; }""";
Console.WriteLine(css);

string set = $$"""{{{value}}}""";
Console.WriteLine(set);

// $$$ when the text itself contains {{ }} (Mustache, Handlebars, Go templates)
string user = "Ann";
string template = $$$"""Hello {{name}}, sent by {{{user}}}""";
Console.WriteLine(template);
.box { color: red; }
{red}
Hello {{name}}, sent by Ann

If the text contains a run of braces that is as long as or longer than the hole delimiter, add another $. The compiler tells you when you got it wrong:

int x = 1;
string a = $"""{"x": {x}}""";   // error CS1056: Unexpected character '{'
string b = $$"""{{{{x}}}}""";   // error CS9006: does not start with enough '$' characters
                                //   to allow this many consecutive opening braces as content

To generate the JSON object {"x": 1}, write $$"""{"x": {{x}}}""".

A word of caution: string interpolation does no escaping. If name contains a ", the JSON above becomes invalid, and the same text interpolated into SQL is an injection hole. Raw strings are great for the fixed part of JSON test data, SQL with parameters, or generated code. For real data, use a serializer, SQL parameters, or a template engine (see Text and HTML templates).

Practical examples

using System.Text.Json;

// a Windows path
string dir = """C:\Program Files\dotnet""";
Console.WriteLine(dir);

// SQL that reads like SQL; the value goes in as a parameter, not interpolated
string table = "users";
string sql = $"""
    SELECT id, name
    FROM {table}
    WHERE name LIKE 'A%'
      AND "createdAt" > @since
    ORDER BY name
    """;
Console.WriteLine(sql);

// a JSON test fixture
var doc = JsonDocument.Parse("""
    {
      "id": 7,
      "title": "Raw strings",
      "tags": ["csharp", "strings"]
    }
    """);
Console.WriteLine(doc.RootElement.GetProperty("tags")[1].GetString());
C:\Program Files\dotnet
SELECT id, name
FROM users
WHERE name LIKE 'A%'
  AND "createdAt" > @since
ORDER BY name
strings

Line endings

The newlines inside a multi-line raw string (and inside a multi-line verbatim string) are the newlines of the source file. If the file has Windows line endings (CRLF), the string contains \r\n. If git checks it out with LF, the string contains \n. The same program can therefore produce different strings on different machines:

string s = """
    a
    b
    """;
Console.WriteLine(s.Contains('\r'));
Console.WriteLine(s.ReplaceLineEndings("\n").Contains('\r'));

Output when the source file uses LF, then CRLF:

False
False
True
False

If the exact bytes matter (hashes, snapshot tests, network protocols), normalize with ReplaceLineEndings("\n"), or pin the line endings of .cs files with .gitattributes (*.cs text eol=lf).

Comparison of string literal kinds

"..." @"..." """..."""
Escape sequences (\n, \t) yes no no
A " in the text \" "" as is
A \ in the text \\ as is as is
Multi-line no yes yes
Indentation removed n/a no yes
Literal { when interpolated {{ {{ as is with $$
Since C# 1 C# 1 C# 11

Raw strings have no escape sequences at all. If you need a tab or another control character inside one, type it literally or use interpolation: $"""a{'\t'}b""".

UTF-8 string literals: the u8 suffix

A lot of code works with UTF-8 bytes rather than .NET strings (which are UTF-16): network protocols, HTTP headers, JSON with Utf8JsonWriter, files. Before C# 11 you converted at run time with Encoding.UTF8.GetBytes. The u8 suffix does the conversion at compile time:

using System.Text;

ReadOnlySpan<byte> hello = "Hello, ü!"u8;
Console.WriteLine($"{hello.Length} bytes: {Convert.ToHexString(hello)}");
Console.WriteLine("Hello, ü!".Length + " chars");

// same bytes as Encoding.UTF8.GetBytes, but computed by the compiler
byte[] runtime = Encoding.UTF8.GetBytes("Hello, ü!");
Console.WriteLine(hello.SequenceEqual(runtime));

// need a byte[]? call ToArray() (this allocates)
byte[] copy = "abc"u8.ToArray();
Console.WriteLine(string.Join(",", copy));

// u8 literals can be concatenated, and raw strings can be u8 too
ReadOnlySpan<byte> request = "GET / HTTP/1.1\r\n"u8 + "Host: example.com\r\n\r\n"u8;
Console.WriteLine(request.Length);

ReadOnlySpan<byte> rawJson = """{"ok": true}"""u8;
Console.WriteLine(Encoding.UTF8.GetString(rawJson));

// no null terminator is part of the span
Console.WriteLine("ab"u8.Length);
10 bytes: 48656C6C6F2C20C3BC21
9 chars
True
97,98,99
37
{"ok": true}
2

ü is one char but two UTF-8 bytes (C3 BC), so the span is 10 bytes long. The bytes are stored in the assembly's data section and the span points straight at them.

Things to know:

static class Protocol
{
    public static ReadOnlySpan<byte> Separator => "\r\n"u8;
}

Where u8 literals are useful

using System.Buffers;
using System.Text;
using System.Text.Json;

// 1. writing protocol bytes straight to a stream
using var ms = new MemoryStream();
ms.Write("HTTP/1.1 200 OK\r\n"u8);
ms.Write("Content-Type: text/plain\r\n\r\n"u8);
ms.Write("hi"u8);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()).Replace("\r\n", "|"));

// 2. comparing incoming bytes without decoding them to a string
byte[] incoming = Encoding.UTF8.GetBytes("PING extra");
if (incoming.AsSpan().StartsWith("PING"u8))
    Console.WriteLine("got PING");

// 3. Utf8JsonWriter property names, and Utf8JsonReader comparisons
var buffer = new ArrayBufferWriter<byte>();
using (var w = new Utf8JsonWriter(buffer))
{
    w.WriteStartObject();
    w.WriteString("name"u8, "Ann"u8);
    w.WriteNumber("age"u8, 41);
    w.WriteEndObject();
}
Console.WriteLine(Encoding.UTF8.GetString(buffer.WrittenSpan));

var reader = new Utf8JsonReader(buffer.WrittenSpan);
while (reader.Read())
{
    if (reader.TokenType == JsonTokenType.PropertyName && reader.ValueTextEquals("age"u8))
    {
        reader.Read();
        Console.WriteLine($"age = {reader.GetInt32()}");
    }
}
HTTP/1.1 200 OK|Content-Type: text/plain||hi
got PING
{"name":"Ann","age":41}
age = 41

Many .NET APIs that deal with bytes have ReadOnlySpan<byte> overloads (Stream.Write, Utf8JsonWriter, Utf8JsonReader.ValueTextEquals, MemoryExtensions.StartsWith/IndexOf/SequenceEqual), and u8 literals plug straight into them. For more on working with bytes, see Bytes and binary data.

Allocation compared with Encoding.UTF8.GetBytes

const int N = 100_000;

Measure("Encoding.UTF8.GetBytes", () => { long t = 0; for (int i = 0; i < N; i++) t += System.Text.Encoding.UTF8.GetBytes("Content-Type").Length; return t; });
Measure("\"...\"u8", () => { long t = 0; for (int i = 0; i < N; i++) t += "Content-Type"u8.Length; return t; });
Measure("\"...\"u8.ToArray()", () => { long t = 0; for (int i = 0; i < N; i++) t += "Content-Type"u8.ToArray().Length; return t; });

static void Measure(string label, Func<long> f)
{
    f();
    long before = GC.GetAllocatedBytesForCurrentThread();
    f();
    long bytes = GC.GetAllocatedBytesForCurrentThread() - before;
    Console.WriteLine($"{label,-24} {bytes / N,3} bytes per call");
}
Encoding.UTF8.GetBytes    40 bytes per call
"..."u8                    0 bytes per call
"..."u8.ToArray()         40 bytes per call

GetBytes encodes the string and allocates a new array every time. The u8 literal does neither. .ToArray() brings the allocation back, so call it once (for example into a static readonly byte[]) rather than in a loop.

The \e escape sequence (C# 13)

Raw strings have no escapes, but regular strings got a new one in C# 13: \e is the ESC character (U+001B), which starts ANSI terminal escape codes for colors and cursor movement:

// \e is the ESC character (U+001B), new in C# 13
Console.WriteLine((int)'\e');
Console.WriteLine("\e" == "\x1b");

string red = "\e[31m";
string bold = "\e[1m";
string reset = "\e[0m";
Console.WriteLine($"{bold}{red}error:{reset} file not found");

// the trap \e avoids: \x takes up to 4 hex digits
Console.WriteLine("\x1bBold".Length);  // \x1bB is one char: U+1BB
Console.WriteLine("\eBold".Length);    // ESC + "Bold"
27
True
error: file not found
4
5

(In a terminal, error: is printed in bold red.)

Before C# 13 people wrote \x1b, which has a trap: \x reads up to four hex digits, so "\x1bBold" is the single character U+01BB followed by old. \e is always exactly one character. The other escape sequences are listed in String Escape Sequences.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents