🔧 C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
C# 11’s u8 suffix produces a ReadOnlySpan<byte> UTF-8 literal, and pattern matching on spans in a switch expression compares byte sequences directly. If one case literal was typed with a visually-identical but differently-encoded Unicode sequence — a lookalike character, or a precomposed accented letter versus a combining-character sequence that renders the same — the UTF-8 bytes differ even though the literals look identical, so the switch silently falls through to a default case instead of the branch that visually appears to match.
🔎 The Problem
ReadOnlySpan<byte> input = GetUserTag(); // pasted from an external source
var result = input switch
{
"caf\u00e9"u8 => "precomposed e-acute", // U+00E9, single code point
_ => "no match" // actually hits this branch
};
// GetUserTag() returned "cafe\u0301"u8 - 'e' + U+0301 combining acute accent.
// Renders identically, encodes to different UTF-8 bytes entirely.
✅ Fix: Compare Bytes Explicitly When a ‘Identical-Looking’ Match Fails
- When a
u8literal switch isn’t matching a case you can visually confirm is “the same text,” dump both sides as byte arrays and compare them directly, since the bug is specifically about a byte-level difference that text rendering hides. - Normalize any string that might contain user-entered or pasted Unicode (via
string.Normalize()) before converting it to UTF-8 bytes for comparison, rather than assuming visually identical source-code literals are guaranteed to be byte-identical. - Prefer ASCII-only
u8literal cases where correctness matters, and reserve non-ASCIIu8comparisons for contexts where you control both sides end to end and can verify the exact byte sequence once.
🚨 Why This Is Dangerous
- A switch that silently falls through to the wrong branch because of an invisible byte-level mismatch can route data down an unintended code path with no exception or warning, and the bug can survive code review indefinitely because every literal involved looks correct on screen.
A u8 literal matches by the bytes it actually contains, not by how the character renders in your editor — and two things that look the same on screen aren’t guaranteed to be the same sequence of bytes underneath.

