C# Reference ยท Types and Literals
UTF-8 string literals
Reference for C# UTF-8 string literals: the u8 suffix, ReadOnlySpan<byte> results, converting to arrays, constant bytes, limits and typical protocol uses.
A UTF-8 string literal is an ordinary string literal followed by the suffix u8. Instead of a string (UTF-16), it produces the UTF-8 encoded bytes, stored by the compiler directly in the assembly's data section. Added in C# 11, it is the cheap way to write protocol tokens, HTTP header names, JSON property names and magic numbers as bytes.
The type of the expression is ReadOnlySpan<byte>. Because it points at static data, creating one costs nothing: no allocation, no encoding at run time.
ReadOnlySpan<byte> hello = "Hello"u8; byte[] copy = "Hello"u8.ToArray();
Try it
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.
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.
Syntax
ReadOnlySpan<byte> bytes = "text"u8; // suffix u8 or U8
| Aspect | Detail |
|---|---|
| Type | ReadOnlySpan<byte>. It can convert to byte[] only through ToArray(), and to a stream with Write(ReadOnlySpan<byte>). |
| Content | The UTF-8 encoding of the literal, without a null terminator. |
| Allowed text | Ordinary, verbatim and raw string literals. Not interpolated strings. |
| Cost | No allocation and no runtime conversion; the bytes live in the assembly data. |
Errors. The text must be a valid string that can be encoded as UTF-8, and it must be known when compiling, so u8 cannot be applied to an interpolated string.
Usage notes
- It is a span, not an array. A
ReadOnlySpan<byte>is aref struct, so it cannot be a field of a class, be boxed, be used acrossawaitor in iterators, or be captured by a lambda. Return it from a property (static ReadOnlySpan<byte> Header => "X"u8;) instead of storing it in a field. - Pair with UTF-8 APIs.
Utf8JsonWriter,Utf8JsonReader,Stream.Write,Socket.Sendand span methods such asStartsWithaccept spans of bytes, so u8 literals avoid allocating strings. - Length is in bytes, not characters;
"cafรฉ"u8.Lengthis 5 though the string has 4 characters. - Use
ToArray()only when needed, since it allocates. If you need astatic readonly byte[], the literal is still the neatest initializer:static readonly byte[] Magic = "PNG"u8.ToArray();. - Version. C# 11 / .NET 7 or later.