Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix String.Create Leaving Unintended Null Characters in the Result Because the Callback Wrote Fewer Characters Than the Requested Length

- 01.11.26 - ErcanOPAK

🔧 Fix String.Create Leaving Unintended Null Characters in the Result Because the Callback Wrote Fewer Characters Than the Requested Length

String.Create’s callback-based overload (the one taking a length, a state object, and a SpanAction delegate) allocates a string of exactly the requested length up front and hands your callback a mutable character span over that already-allocated buffer, trusting the callback to fill every position before the string is handed back as an ordinary, immutable System.String. The API’s contract is that the callback is responsible for writing to the entire span; it isn’t an auto-sized buffer that trims itself down to whatever you actually wrote, and a callback that writes fewer characters than length promised — because it under-calculated the needed length, or because a conditional branch inside it skips writing to part of the span under some input — doesn’t produce a short string or throw an error, it produces a string of exactly the originally requested length with whatever was left in the backing memory (ordinarily the zero/null character for freshly allocated memory) sitting in the positions the callback never touched.

🔎 The Problem

public static string FormatCode(int prefix, int suffix)
{
    string prefixStr = prefix.ToString();
    string suffixStr = suffix.ToString();

    // Mistake: length calculation assumes a fixed-width suffix,
    // but suffix can legitimately be shorter (e.g. suffix = 7
    // formats as "7", not "0007")
    int totalLength = prefixStr.Length + 1 + 4; // assumes 4-digit suffix

    return string.Create(totalLength, (prefixStr, suffixStr), (span, state) =>
    {
        state.prefixStr.AsSpan().CopyTo(span);
        span[state.prefixStr.Length] = '-';
        // Only writes suffixStr.Length characters here, which can
        // be LESS than the 4 reserved - the callback does nothing
        // for whatever positions are left over at the end
        state.suffixStr.AsSpan().CopyTo(
            span.Slice(state.prefixStr.Length + 1));
    });
}

string code = FormatCode(482, 7);
Console.WriteLine(code.Length);        // 8 (prefix "482" + "-" + 4 reserved)
Console.WriteLine(code);                // "482-7" followed by three
                                          // untouched positions still
                                          // hold the allocator's
                                          // leftover null characters,
                                          // invisible in most console
                                          // output but very much
                                          // present in the string's
                                          // actual character data

✅ Fix: Make the Callback Fill Every Position It Was Given, Every Time

  • Compute length from the actual runtime values being written (prefixStr.Length + 1 + suffixStr.Length here), not from an assumed fixed width, so the requested length and what the callback actually writes always match exactly regardless of input.
  • If a value’s formatted width genuinely can vary and you want fixed-width output, explicitly pad inside the callback (writing literal padding characters into the unused span positions) rather than leaving them untouched and hoping the backing memory happens to contain something harmless.
  • Add a debug-only assertion inside the callback that checks every branch actually advances to the full span length before returning, which catches a conditional path that silently skips writing part of the span during development rather than shipping a string with embedded null characters to production.

🚨 Why This Is Dangerous

  • A string with trailing or embedded null characters looks completely normal when printed to a console or most UI text controls, but can fail string comparisons, break when passed to native interop or file I/O that treats a null character as a terminator, or silently corrupt anything downstream that assumes string.Length characters of real content.

string.Create hands you a buffer of exactly the length you asked for and trusts you to fill every position in it — it has no way to know your callback meant to write less, so whatever you leave untouched just stays whatever the allocator happened to put there.

— C# Best Practice

Related posts:

C#: Implement Rate Limiting with Async/Await

C#: Implement Rate Limiting with Async/Await

C# Memory Leak: Event Handlers Never Unsubscribe

C# Memory Leak: Event Handlers Never Unsubscribe

C#: Why Modifying a Collection While Foreach-ing Over It Throws (And the Safe Way to Do It)

C#: Why Modifying a Collection While Foreach-ing Over It Throws (And the Safe Way to Do It)

Views: 6

Post navigation

Visual Studio: Fix CodeLens Reference Counts Freezing on an Old Number Because the Background Index Build Silently Stopped After a Solution Filter Was Applied
ASP.NET Core: Fix a Custom ProblemDetails Response Losing Its Extra Fields Because a Second Registered Writer Runs After Yours and Overwrites Them

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (608)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (546)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com