ZetCode

C# UTF-8 string literals

last modified November 15, 2026

This article shows how to use UTF-8 string literals in C#. We cover the u8 suffix, the difference between bytes and characters, raw string literals, writing to streams, JSON, and the Utf8 helpers that validate UTF-8 input.

A UTF-8 string literal is a string literal with the u8 suffix. The compiler encodes the text as UTF-8 and stores the bytes in the assembly, and the expression has the type ReadOnlySpan<byte>. Reading the literal allocates no memory and performs no conversion: the bytes are already in the form that sockets, HTTP, JSON, and hashing APIs expect.

Before C# 11, the usual way to get UTF-8 was Encoding.UTF8.GetBytes("text"), which allocates a new byte[] on every call. A u8 literal is a view over constant data, so it is both cheaper and harder to misuse. The suffix works with regular, verbatim, and raw string literals, but not with interpolated strings.

The u8 suffix

Appending u8 to a string literal produces a ReadOnlySpan<byte> containing the UTF-8 encoding of the text. The span can be indexed, sliced, and passed to any API that accepts a byte span.

Program.cs
using System.Text;

ReadOnlySpan<byte> hello = "Hello"u8;

Console.WriteLine(hello.Length);
Console.WriteLine(string.Join(' ', hello.ToArray()));
Console.WriteLine(Encoding.UTF8.GetString(hello));

The literal has five bytes, one per ASCII character. The code prints the length, the individual byte values, and decodes the span back to a string.

ReadOnlySpan<byte> hello = "Hello"u8;

The declared type is not optional: u8 literals are always ReadOnlySpan<byte>. Assigning one to a byte[] does not compile, because that would require a mutable copy. Calling ToArray() creates such a copy when an API demands an array, but the copy defeats the purpose of the literal.

Console.WriteLine(Encoding.UTF8.GetString(hello));

Encoding.UTF8.GetString has an overload that takes a ReadOnlySpan<byte>, so no intermediate array is needed. The reverse operation, Encoding.UTF8.GetBytes, always allocates a new array, which is why the literal is preferable when the text is known at compile time.

$ dotnet run
5
72 101 108 108 111
Hello

Bytes and characters

A string is a sequence of UTF-16 code units; a UTF-8 literal is a sequence of bytes. The two lengths differ as soon as the text leaves the ASCII range. Characters outside ASCII take two or more bytes in UTF-8, and characters outside the Basic Multilingual Plane take two UTF-16 code units as well.

Program.cs
using System.Text;

const string text = "Příliš žluťoučký kůň";
ReadOnlySpan<byte> utf8 = "Příliš žluťoučký kůň"u8;

Console.WriteLine($"chars: {text.Length}");
Console.WriteLine($"bytes: {utf8.Length}");
Console.WriteLine(Encoding.UTF8.GetString(utf8));

The Czech pangram has 20 UTF-16 code units and 29 UTF-8 bytes. Both forms describe the same text, and decoding the bytes returns the original string.

ReadOnlySpan<byte> utf8 = "Příliš žluťoučký kůň"u8;

The compiler reads the source file as UTF-8 and encodes the literal with the same encoding. This works only if the source file itself is saved as UTF-8, which is the default for C# projects. A UTF-8 literal is therefore a convenient way to keep non-ASCII text in the assembly without a runtime conversion.

$ dotnet run
chars: 20
bytes: 29
Příliš žluťoučký kůň

Raw string literals

The u8 suffix also applies to raw string literals. Raw literals are useful for JSON, XML, and multi-line text because they do not require escaped quotes or newline escapes. The suffix goes after the closing quote sequence.

Program.cs
using System.Text;

ReadOnlySpan<byte> raw = """
    Hello
    World
    """u8;

Console.WriteLine(raw.Length);
Console.WriteLine(Encoding.UTF8.GetString(raw));

The raw literal contains the two lines without the indentation and without a trailing newline. Its UTF-8 form has eleven bytes: five for Hello, one for the newline, and five for World.

ReadOnlySpan<byte> raw = """
    Hello
    World
    """u8;

The closing delimiter determines the indentation that is removed from every line. The suffix must follow the delimiter, not the last content line. A verbatim literal such as @"C:\temp"u8 works the same way, and both forms can contain non-ASCII text.

$ dotnet run
11
Hello
World

Streams and buffers

One of the main uses of UTF-8 literals is writing protocol text without a conversion. Stream.Write accepts a ReadOnlySpan<byte>, so a literal can be written directly. The same is true for Socket.Send, PipeWriter.Write, and many other span-based APIs.

Program.cs
using System.Text;

using var stream = new MemoryStream();
stream.Write("Hello, "u8);
stream.Write("world!"u8);

Console.WriteLine(stream.Length);
Console.WriteLine(Encoding.UTF8.GetString(stream.ToArray()));

Two literals are appended to a MemoryStream. The stream holds thirteen bytes, and decoding them produces the complete sentence.

stream.Write("Hello, "u8);
stream.Write("world!"u8);

Each call binds to Stream.Write(ReadOnlySpan<byte>). There is no temporary array and no encoding step. If the target API has only a byte[] overload, ToArray() is the bridge, but the allocation is then unavoidable.

$ dotnet run
13
Hello, world!

JSON in UTF-8

System.Text.Json works natively with UTF-8. JsonSerializer.Deserialize has an overload that accepts a ReadOnlySpan<byte>, and SerializeToUtf8Bytes returns UTF-8 bytes. A literal can therefore hold a small JSON document without a string conversion.

Program.cs
using System.Text;
using System.Text.Json;

ReadOnlySpan<byte> json = """{"name":"Alice","age":30}"""u8;
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);

var person = JsonSerializer.Deserialize<Person>(json, options);
Console.WriteLine($"{person!.Name} {person.Age}");

ReadOnlySpan<byte> output = JsonSerializer.SerializeToUtf8Bytes(person, options);
Console.WriteLine(Encoding.UTF8.GetString(output));

public sealed record Person(string Name, int Age);

The web defaults make the serializer accept the camel-case property names and write them back in the same style. The input is read straight from the literal, and the output is decoded only for display.

var person = JsonSerializer.Deserialize<Person>(json, options);

The overload takes the span directly. Without the options, System.Text.Json is case-sensitive by default, so the camel-case name property would not bind to the Pascal-case Name property. JsonSerializerDefaults.Web enables case-insensitive matching and camel-case output.

$ dotnet run
Alice 30
{"name":"Alice","age":30}

Validating UTF-8

Not every byte sequence is valid UTF-8. The System.Text.Unicode.Utf8 class provides IsValid and IndexOfInvalidSubsequence, which report whether a span is well-formed and where the first error is. The check does not allocate and does not throw.

Program.cs
using System.Text.Unicode;

ReadOnlySpan<byte> valid = "Hello"u8;
ReadOnlySpan<byte> invalid = [0xC3, 0x28];

Console.WriteLine(Utf8.IsValid(valid));
Console.WriteLine(Utf8.IsValid(invalid));
Console.WriteLine(Utf8.IndexOfInvalidSubsequence(invalid));
Console.WriteLine(Utf8.IndexOfInvalidSubsequence(valid));

The first span is ASCII and valid. The second starts a two-byte sequence with 0xC3 but continues with 0x28, which is not a valid continuation byte, so the error is reported at index 0. A valid span returns -1.

ReadOnlySpan<byte> invalid = [0xC3, 0x28];

The collection expression creates a two-byte span on the stack. A literal such as "Hello"u8 is valid for its own text, but data from a socket, a file, or a request is not guaranteed to be. Validating before decoding turns a vague DecoderFallbackException into a precise error position.

$ dotnet run
True
False
0
-1

Limits of u8 literals

The u8 suffix applies only to string literals, not to interpolated strings, nameof results, or strings built at run time. The text must be fixed at compile time, so it cannot contain a value that is known only when the program runs. When the text is dynamic, encode it with Encoding.UTF8.GetBytes, write it through an Utf8JsonWriter, or use an interpolated string handler that writes UTF-8 directly.

Unlike an ordinary string literal, a UTF-8 literal is not a C# compile-time constant. It cannot be used as the default value of an optional parameter, and it cannot appear in a const declaration. Two adjacent u8 literals can be concatenated at compile time, but a u8 literal cannot be combined with a regular string in the same expression.

A ReadOnlySpan<byte> is a ref struct, so it cannot be stored in a field of a class, captured by a lambda, or used as a generic type argument in most positions. A static property can return a literal on each call: static ReadOnlySpan<byte> Marker => "marker"u8;. The span points into the assembly's data, so returning it is cheap. If the bytes must outlive the call or be stored, copy them to a byte[] with ToArray() or to ReadOnlyMemory<byte>.

The Encoding, Span, and JSON tutorials cover the surrounding APIs. The byte array to hex string tutorial shows how to display raw UTF-8 bytes when debugging.

Source

UTF-8 string literals

Utf8 class

Encoding.UTF8

In this article we have used UTF-8 string literals in C#. See also the Encoding, Span, JSON, and StreamWriter tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.