skip to content

In .NET, how does `string.Create<TState>(int, TState, SpanAction<char, TState>)` build a URL slug without an intermediate buffer, and what must its callback respect?

level: seniorimportance: nice to knowfreq 18%

answer

  1. allocate first, fill second
  2. length known up front
  3. a Span over the new string
  4. state plus a static lambda
  5. every slot written once

basics

~20 s

string.Create allocates the final string once at the given length and hands its characters to your callback as a Span<char>. You need the exact length first, must write every slot, and should pass inputs as state to a static lambda.

solid answer

~50 s

`string.Create<TState>(int length, TState state, SpanAction<char, TState> action)` allocates a string of exactly `length` characters, calls `action` with a `Span<char>` over that string's memory plus your `state`, and returns the string, with no second copy. Other routes write the text somewhere first: a `char[]` or a `StringBuilder` and then a copy into a new string. For a slug you make one pass to measure the output (letters and digits, one `-` per gap) and a second pass inside the callback to write it. The rules: know the exact length before the call, write every position (an unwritten slot stays `'\0'`, and writing past the end throws `IndexOutOfRangeException`), never keep the span or change the string after `Create` returns, and pass inputs as `state` to a `static` lambda so no closure is allocated. Since .NET 9, `TState` is marked `allows ref struct`, so the state can be a `ReadOnlySpan<char>`.

code

csharp · 28 lines
csharp
Console.WriteLine(Slug("  Ergo Chair -- Mesh Back (2026) "));   // ergo-chair-mesh-back-2026
Console.WriteLine(Slug("!!!") == string.Empty);                    // True

static string Slug(string name)
{
    int length = 0;
    bool gap = false;
    foreach (char c in name)                  // pass 1: measure
    {
        if (!char.IsAsciiLetterOrDigit(c)) { gap = true; continue; }
        if (gap && length > 0) length++;      // room for one '-'
        length++;
        gap = false;
    }

    return string.Create(length, name, static (span, source) =>
    {
        int i = 0;                            // pass 2: write every slot exactly once
        bool gap = false;
        foreach (char c in source)
        {
            if (!char.IsAsciiLetterOrDigit(c)) { gap = true; continue; }
            if (gap && i > 0) span[i++] = '-';
            span[i++] = char.ToLowerInvariant(c);
            gap = false;
        }
    });
}

go deeper

for a junior

Recall that string.Create makes a string of a given length and lets a callback fill its characters through a Span<char>, saving the usual buffer-then-copy step.

for a middle

Explain the signature: length, state and SpanAction<char, TState>; the span covers the new string; and why the length must be known before the call.

for a senior

Show the failure modes: unwritten slots left as '\0', IndexOutOfRangeException past the end, closures from capturing lambdas, and measuring and writing passes that drift apart.

for a principal

Decide where the extra complexity pays: hot paths producing many computable-length strings, measured with allocation counts, while ordinary code keeps +, string.Join or StringBuilder.

## The problem string.Create solves A .NET `string` is immutable once it is handed out, so code that builds text character by character usually writes into scratch space first and then copies: - `new char[n]`, fill it, then `new string(chars)`: two allocations and a copy. - `StringBuilder`, then `ToString()`: a builder, its buffer and a final copy. - `stackalloc char[n]` into a `Span<char>`, then `new string(span)`: no heap scratch, but still a copy, and stack space limits `n`. `string.Create` removes the scratch step. Its signature in the runtime source is: ```csharp public static string Create<TState>(int length, TState state, SpanAction<char, TState> action) where TState : allows ref struct ``` `SpanAction<T, TArg>` is a delegate in `System.Buffers` declared as `void SpanAction<T, in TArg>(Span<T> span, TArg arg)`. ## How the call works 1. If `length` is 0, it returns `string.Empty` without calling the callback; a negative length throws `ArgumentOutOfRangeException`, and a null `action` throws `ArgumentNullException`. 2. It allocates a string of exactly `length` characters, the same internal allocation every string uses. 3. It calls `action` with a `Span<char>` covering that string's characters and the `state` you passed. 4. It returns the string. The characters you wrote are the string; nothing is copied afterwards. The string is mutable only inside that window, and only through the span. ## The rules your callback must follow - **Know the exact length first.** The string cannot grow or shrink. A slug, a fixed-width key or a hex dump each have a length you can compute; free-form text whose length you discover while writing does not fit this API. - **Write every position.** Unwritten characters are not trimmed. In a test, `string.Create(3, 0, static (span, _) => span[0] = 'a')` returned a three-character string whose last two characters were `'\0'`. - **Stay inside the span.** Writing `span[length]` throws `IndexOutOfRangeException` from the span's bounds check. - **Do not let the span escape.** `Span<char>` is a ref struct, so the compiler already rejects storing it in a class field (CS8345). Never use unsafe code to keep writing after `Create` returns: by then the string may be shared, hashed or used as a dictionary key. - **Pass inputs as `state` to a `static` lambda.** A lambda that captures locals makes the compiler allocate a closure object and a new delegate; a `static` lambda cannot capture, so the compiler caches its delegate, and the input travels through `state` instead. ## A slug generator in two passes The slug for `" Ergo Chair -- Mesh Back (2026) "` is `"ergo-chair-mesh-back-2026"`: ASCII letters and digits lowercased, every run of other characters collapsed into one `-`, none at either end. The first pass counts output characters with the same rules the second pass writes with; the second pass runs inside `string.Create`. Keeping the two loops identical in logic is the price of the API: if they disagree, the string ends with `'\0'` characters or the callback throws. ## Span state since .NET 9 On .NET 8 the `TState` type argument could not be a ref struct, so a slice of a larger string had to be passed as a string, a tuple of string and offsets, or a captured local. In .NET 9 the libraries annotated `TState` with **`allows ref struct`**, the C# 13 anti-constraint, so `ReadOnlySpan<char>` is now a legal state: ```csharp ReadOnlySpan<char> name = "Desk Lamp".AsSpan(); string lower = string.Create(name.Length, name, static (span, src) => src.ToLowerInvariant(span)); ``` ## When it is worth it | Approach | Scratch space | Copies into the string | |---|---|---| | `char[]` then `new string(chars)` | heap array | one | | `StringBuilder` then `ToString()` | builder and chunks | one | | `stackalloc` then `new string(span)` | stack, size-limited | one | | `string.Create` | none | none: written in place | `string.Create` earns its two-pass complexity in hot paths that produce many short strings with a computable length: slug or key generators, ID formatting, encoders. For one-off text, `+`, `string.Join` or a `StringBuilder` are clearer, and the saving is a single small allocation and copy.

  • Why not `stackalloc` a buffer and call `new string(span)` instead?
    That works for short results, but the characters are written twice, once into stack memory and once when the string constructor copies them, and stack space is small, so long or unbounded input needs a heap fallback. `string.Create` writes straight into the string's own memory, so there is no copy and no stack-size limit.
  • Can you pass a `ReadOnlySpan<char>` as the state argument?
    Yes, from .NET 9: `TState` is annotated `allows ref struct`, the C# 13 anti-constraint, so `string.Create(name.Length, name.AsSpan(), static (span, src) => src.ToLowerInvariant(span))` compiles. On .NET 8 a span cannot be a generic type argument, so you passed the string itself or a tuple carrying it.
  • What happens if the measuring pass and the writing pass disagree on the length?
    If the writer produces fewer characters, the extra slots stay `'\0'` and the string silently carries them; if it produces more, `span[i++]` runs past the end and throws `IndexOutOfRangeException`. Sharing one rule set between both passes, and testing edge inputs such as an empty or all-punctuation name, is part of using the API.

  • You can call string.Create before knowing the final length and trim it afterwards.
  • Unwritten characters are trimmed off the string string.Create returns.
  • Capturing locals in the callback lambda costs nothing extra.
  • Keeping the span to fill the string in later is fine, because the string lives on.
  • string.Create is the right default for every small concatenation.

Assumes .NET 10; string.Create's TState has accepted a ref struct such as ReadOnlySpan<char> since .NET 9 (the C# 13 allows ref struct anti-constraint).