skip to content

In C# 11 and later, what does a "PING"u8 literal produce, and when would you use it instead of Encoding.UTF8.GetBytes?

level: middleimportance: nice to knowfreq 22%

answer

  1. a suffix on a string literal
  2. bytes known at compile time
  3. a read-only span type
  4. not a constant expression

basics

~20 s

A u8 suffix makes the compiler encode the literal to UTF-8 at compile time and type it as ReadOnlySpan<byte>, so the call site allocates nothing. Use it for fixed protocol text; use Encoding.UTF8.GetBytes for strings known only at run time.

solid answer

~40 s

Since C# 11, `"PING"u8` is a **UTF-8 string literal**: the compiler encodes it once, stores the bytes in the assembly and types the expression as `ReadOnlySpan<byte>`, with a null terminator after the bytes but outside `Length`. Evaluating it does not allocate, whereas `Encoding.UTF8.GetBytes` encodes at run time and returns a new `byte[]` each call. The type sets the limits: assigning it to `Span<byte>` or `byte[]` is error CS0029 (use `.ToArray()`), it is not a constant so it cannot be a default parameter value (CS1736), and two `u8` literals joined with `+` fold into one. Use it for fixed keywords, delimiters and header names written to byte APIs; user text still goes through `Encoding.UTF8`.

code

csharp · 14 lines
csharp
using System.Text;

ReadOnlySpan<byte> greeting = "héllo"u8;
Console.WriteLine(greeting.Length);
Console.WriteLine(Convert.ToHexString(greeting));

byte[] atRunTime = Encoding.UTF8.GetBytes("héllo");
Console.WriteLine(greeting.SequenceEqual(atRunTime));

ReadOnlySpan<byte> frame = "PING "u8 + "chat"u8;
Console.WriteLine(Encoding.UTF8.GetString(frame));

byte[] copy = "héllo"u8.ToArray();
Console.WriteLine(copy.Length);

go deeper

for a junior

Recall the u8 suffix from C# 11, that it gives UTF-8 bytes instead of a string, and that its type is ReadOnlySpan<byte>.

for a middle

Explain compile-time encoding and why the call site does not allocate, then list the limits that follow from the type: read-only, not a constant, ToArray for a byte array.

for a senior

Choose between u8, Encoding.UTF8.GetBytes and the span overload of GetBytes on a hot path, and size buffers with GetByteCount or GetMaxByteCount rather than Length.

for a principal

In a protocol or serializer codebase, encourage u8 for fixed tokens and cached arrays where byte[] is required, so per-message encoding of constant text is not repeated everywhere.

## What the compiler does with `u8` C# 11 added **UTF-8 string literals**: a string literal followed by the suffix `u8`, such as `"PING"u8`. The compiler encodes the text to UTF-8 at **compile time** and gives the expression the type `ReadOnlySpan<byte>`. The bytes are stored in the assembly's data, and the span points at them, so evaluating the literal does not allocate. A null terminator is placed after the last byte in memory, outside the span's `Length`, for interop with APIs that expect null-terminated strings. Compare that with `Encoding.UTF8.GetBytes("PING")`, which encodes on every call and returns a new `byte[]`. Measured with `GC.GetAllocatedBytesForCurrentThread()` around 1,000 iterations of each on .NET 10, the `u8` loop allocated 0 bytes and the `GetBytes` loop 40,000 bytes — one new array per call. ## The type and its limits | Code | Result | |---|---| | `ReadOnlySpan<byte> s = "abc"u8;` | compiles; `s.Length` is 3 | | `var s = "abc"u8;` | compiles; `var` is `ReadOnlySpan<byte>` | | `Span<byte> s = "abc"u8;` | error CS0029 — the bytes are read-only | | `byte[] s = "abc"u8;` | error CS0029 — call `.ToArray()` for an array | | `"PING "u8 + "chat"u8` | compiles; folded into one literal of 9 bytes | | a `u8` literal as a default parameter value | error CS1736 — it is not a constant | | `"\uD83D"u8` (a lone surrogate) | error CS9026 — the text cannot be converted to UTF-8 | A few rules follow from the type: - A `u8` literal **has no constant value**, because `ReadOnlySpan<byte>` cannot be the type of a constant. It cannot initialize a `const` or appear as a default parameter value. - It is a **span**, a `ref struct`, so it cannot be stored in a class field; a `static ReadOnlySpan<byte> Ping => "PING"u8;` property is the usual way to name one, and it does not allocate either. The full span rules belong to the lesson on spans. - `+` is defined only between two `u8` operands; `"a"u8 + "b"` is error CS0019, because a span and a `string` cannot be added. - There is no interpolated form — `$"..."u8` is a syntax error — because the bytes must be known at compile time. ## `u8` literals vs `Encoding.UTF8` Both produce the same bytes for the same text — the snippet checks it with `SequenceEqual`. The difference is *when* encoding happens and *what* you get back: - `"..."u8` — encoded once by the compiler; a read-only span over static data; text must be a literal. - `Encoding.UTF8.GetBytes(string)` — encoded at run time; a new `byte[]` each call; works for any string, including user input. - `Encoding.UTF8.GetBytes(ReadOnlySpan<char>, Span<byte>)` — encoded at run time into a buffer you supply, so you control allocation. Neither adds a byte order mark. `Encoding.UTF8.GetPreamble()` returns the three bytes `EF BB BF` because the instance is configured to emit an identifier, but `GetBytes` encodes only the characters. ## Counting bytes `string.Length` counts UTF-16 code units, not bytes: "héllo" has `Length` 5 but 6 UTF-8 bytes, because é takes two. Two `Encoding` methods size a buffer: 1. `Encoding.UTF8.GetByteCount(string)` scans the text and returns the exact count. 2. `Encoding.UTF8.GetMaxByteCount(int)` returns a worst-case bound from the char count alone — 123 for 40 chars — which is cheaper when an oversized buffer is acceptable. ## When to choose which 1. **Fixed protocol text** — frame keywords, header names, delimiters and other tokens handed to APIs that take bytes: use `u8`. 2. **Text known only at run time** — usernames, messages: use `Encoding.UTF8`, preferably the span overload into a pooled or stack buffer on hot paths. 3. **An API that needs `byte[]`** — call `.ToArray()` on the literal once and cache the array in a `static readonly` field, rather than converting on every call. A quick way to tell whether a codebase would benefit is to search for `Encoding.UTF8.GetBytes("` with a literal argument: every hit encodes the same constant text again on each call, and each one is a candidate for a `u8` literal or, where an array is required, a cached `static readonly byte[]`. The interview point is the trade: `u8` moves encoding to the compiler and removes the allocation, at the price of read-only span semantics and no run-time text.

  • Can a u8 literal be the default value of a ReadOnlySpan<byte> parameter?
    No. A `u8` literal has no constant value, because `ReadOnlySpan<byte>` cannot be the type of a constant, so the compiler reports CS1736, "Default parameter value for 'frame' must be a compile-time constant". Add an overload without the parameter that passes the literal to the main method instead.
  • Does Encoding.UTF8.GetBytes put a byte order mark in front of the bytes it returns?
    No. `Encoding.UTF8` is configured to emit a UTF-8 identifier, which `GetPreamble()` returns as `EF BB BF`, but `GetBytes` encodes only the characters you pass. A `u8` literal never carries a preamble either; writing one is a separate, explicit step.
  • How do you size a buffer before encoding a chat message to UTF-8?
    `Encoding.UTF8.GetByteCount(string)` scans the text and returns the exact byte count. `Encoding.UTF8.GetMaxByteCount(int)` returns a worst-case bound from the char count alone — 123 for 40 chars — which avoids the scan when an oversized buffer is fine. `string.Length` is neither: it counts UTF-16 code units.

  • A u8 literal has type byte[], so callers can store and modify it.
  • u8 literals are encoded at run time on each call, just like GetBytes.
  • A u8 literal is a compile-time constant usable in const and default parameters.
  • The span's Length includes the trailing null terminator.
  • You can write an interpolated u8 literal such as $"PING {name}"u8.