Skip to content
Tutorials Center
My learning

Topics

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.

C#
ReadOnlySpan<byte> hello = "Hello"u8;
byte[] copy = "Hello"u8.ToArray();

Try it

C# Bytes from 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.

C# Using u8 literals with a stream

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

C#
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 a ref struct, so it cannot be a field of a class, be boxed, be used across await or 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.Send and span methods such as StartsWith accept spans of bytes, so u8 literals avoid allocating strings.
  • Length is in bytes, not characters; "cafรฉ"u8.Length is 5 though the string has 4 characters.
  • Use ToArray() only when needed, since it allocates. If you need a static readonly byte[], the literal is still the neatest initializer: static readonly byte[] Magic = "PNG"u8.ToArray();.
  • Version. C# 11 / .NET 7 or later.