In .NET, what does string.EnumerateRunes() give you that a foreach over the string's chars does not, and where does a Rune still fall short?
answer
- scalar value, not code unit
- a struct in System.Text
- pairs joined, lone halves replaced
- flags and accents still split
basics
~20 sEnumerateRunes yields System.Text.Rune values, one per Unicode scalar value, so a surrogate pair arrives as one item and a lone surrogate as U+FFFD. A flag, a ZWJ emoji or an accented letter can still span several runes.
solid answer
~40 sA `foreach` over a string yields UTF-16 code units, so an emoji arrives as two meaningless halves. `string.EnumerateRunes()` yields `System.Text.Rune` values — whole Unicode scalar values — joining each surrogate pair and replacing an unpaired surrogate with `Rune.ReplacementChar` (U+FFFD) instead of throwing. A `Rune` exposes `Value`, `Utf16SequenceLength`, `Utf8SequenceLength` and classification such as `Rune.IsLetter` that sees the whole code point. Where it falls short is user-perceived characters: the Georgian flag is two runes, the three-person family emoji joined with ZERO WIDTH JOINER is five, and `e` plus a combining accent is two. For those, `StringInfo` and its text elements are the right unit.
code
csharp · 18 linesusing System.Globalization;
using System.Text;
string[] samples = ["abc", "👍", "🇬🇪", "é", "👨👩👧"];
foreach (string s in samples)
{
int runes = 0;
foreach (Rune r in s.EnumerateRunes()) runes++;
int elements = new StringInfo(s).LengthInTextElements;
Console.WriteLine($"chars={s.Length} runes={runes} textElements={elements}");
}
string broken = "👍".Substring(0, 1); // a lone high surrogate
foreach (Rune r in broken.EnumerateRunes())
Console.WriteLine($"U+{r.Value:X4} {r == Rune.ReplacementChar}");
try { _ = new Rune(broken[0]); }
catch (ArgumentOutOfRangeException) { Console.WriteLine("new Rune(char) rejects a surrogate"); }go deeper
Recall that Rune lives in System.Text, holds one whole code point, and that EnumerateRunes walks a string rune by rune instead of char by char.
Explain what EnumerateRunes does with a valid pair and with a lone surrogate, and name Utf16SequenceLength, Utf8SequenceLength and the throwing versus Try-style ways to build a Rune.
Show where runes still break real text — flags, ZWJ emoji, combining accents — and say when you switch to StringInfo text elements, and when U+FFFD in the output signals corrupted input upstream.
Name the unit a shared text utility works in and document it; mixing char, rune and text-element counts across services is how limits disagree between client and server.
## Three units of text in .NET .NET gives you three different answers to "how long is this string", and each comes from its own type: | Unit | .NET type or API | What one item is | |---|---|---| | UTF-16 code unit | `char`, `string.Length` | 16 bits; half of a pair for code points above U+FFFF | | Unicode scalar value | `System.Text.Rune`, `string.EnumerateRunes()` | one whole code point, U+0000–U+10FFFF minus the surrogate range | | Text element | `System.Globalization.StringInfo` | one user-perceived character (an extended grapheme cluster) | Running the snippet below on the .NET 10 SDK gives these counts: | Sample | chars | runes | text elements | |---|---|---|---| | `abc` | 3 | 3 | 3 | | 👍 | 2 | 1 | 1 | | 🇬🇪 (Georgian flag) | 4 | 2 | 1 | | `e` + U+0301 | 2 | 2 | 1 | | 👨👩👧 (family) | 8 | 5 | 1 | A foreach over a string's `char`s gives you the first column's units. `EnumerateRunes()` gives you the second. Read the rows top to bottom and the pattern is clear: ASCII agrees on all three counts; an emoji outside the BMP is where `char` and `Rune` part ways; and flags, combining accents and ZWJ sequences are where `Rune` and the text element part ways. Code that must be right for all of them has to say which column it means, because no single count is correct for every task. ## What `Rune` gives you `System.Text.Rune` is a read-only struct that wraps one **Unicode scalar value** — any code point except the surrogate range U+D800–U+DFFF. Its useful members: - `Value` — the code point as an `int`. - `Utf16SequenceLength` — 1 or 2, how many `char`s the rune occupies in a string. - `Utf8SequenceLength` — 1 to 4, how many bytes it occupies in UTF-8. - `IsBmp` — whether it fits in a single `char`. - Static classification and casing that see the whole code point: `Rune.IsLetter(Rune)`, `Rune.IsDigit(Rune)`, `Rune.ToUpperInvariant(Rune)` and friends. `char.IsLetter(char)` given only the high surrogate of a supplementary letter returns false; `Rune.IsLetter` on the combined rune returns true. - `Rune.ReplacementChar` — U+FFFD, the standard stand-in for invalid data. Construction is strict. `new Rune(char)` throws `ArgumentOutOfRangeException` when the `char` is a surrogate, because half a pair is not a scalar value, and `new Rune(int)` throws for a value outside the scalar range. For untrusted input use the non-throwing readers: `Rune.TryGetRuneAt(string, int, out Rune)`, or `Rune.DecodeFromUtf16(ReadOnlySpan<char>, out Rune, out int)`, which returns an `OperationStatus`. ## How `EnumerateRunes` treats broken input `string.EnumerateRunes()` returns a `StringRuneEnumerator`, a struct, so a plain `foreach` over it does not allocate (LINQ operators reach it through `IEnumerable<Rune>` and box it). On each step it calls `Rune.TryGetRuneAt` at the current index: 1. A BMP character becomes a rune of length 1. 2. A valid surrogate pair becomes **one** rune of length 2 — the main thing a `char` loop cannot give you. 3. An unpaired surrogate becomes `Rune.ReplacementChar`, U+FFFD, and the enumeration moves on by one `char`. It never throws. So `EnumerateRunes()` is a safe way to walk text you did not produce, and the presence of U+FFFD in the output tells you the input was not well-formed UTF-16. ## Where runes are the right unit - Computing UTF-8 size rune by rune (`Utf8SequenceLength`), for example when splitting text into byte-limited chunks. - Classifying or case-mapping characters outside the BMP, where `char` APIs see only half. - Validating that a string is well-formed before you encode it, by looking for replacement runes. - Checking for specific code points, such as banning a range of emoji in nicknames. ## Where runes are not enough A rune is still not what a person calls a character. A flag is two regional-indicator runes, an emoji family is several emoji joined by U+200D ZERO WIDTH JOINER, and a letter with a combining accent is a base rune plus a combining rune. Counting, truncating or reversing by runes therefore still breaks these. For user-perceived characters, use `StringInfo`: `LengthInTextElements`, `StringInfo.GetNextTextElementLength(string, int)` or `StringInfo.GetTextElementEnumerator(string)`, which follow the Unicode extended grapheme cluster rules. In short: `char` is storage, `Rune` is meaning at the code-point level, and a text element is what the user sees. Pick the unit that matches the question being asked.
- How do you get a string's UTF-8 byte count from its runes, and is there a shortcut?Summing `Utf8SequenceLength` over `EnumerateRunes()` gives it, and counts each unpaired surrogate as 3 bytes because it arrives as U+FFFD. `Encoding.UTF8.GetByteCount(string)` returns the same number without your own loop, so production code calls that and keeps the rune loop for cases such as cutting text into byte-limited chunks.
- Why does new Rune(s[i]) throw on some strings, and what should a parser call instead?`new Rune(char)` throws `ArgumentOutOfRangeException` when the char is a surrogate, because half a pair is not a scalar value. `Rune.TryGetRuneAt(string, int, out Rune)` reads a whole pair at an index and returns false for invalid data, and `Rune.DecodeFromUtf16(ReadOnlySpan<char>, out Rune, out int)` reports an `OperationStatus`, so a parser can handle bad input without exceptions.
- A Rune is the same thing as one user-perceived character.
- Rune is a 16-bit type like char, only with extra helper methods.
- EnumerateRunes throws as soon as it meets an unpaired surrogate.
- new Rune(char) accepts any char, including either half of a surrogate pair.
- Counting runes always matches StringInfo.LengthInTextElements.