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 a Span Captured by a Lambda Throwing at Runtime

- 19.11.26 - ErcanOPAK

🔧 Fix a Span Captured by a Lambda Throwing at Runtime

`Span<T>` is a `ref struct`, which the compiler restricts from being used inside a closure because a `ref struct` can point to stack-allocated or interior memory the garbage collector doesn’t track the way it tracks heap references, while a closure’s captured variables get hoisted into a heap-allocated object so they can outlive the method that created them. The compiler catches the most obvious violations at compile time with error CS8175, but a span passed indirectly through a generic wrapper, or into a local function later converted to a delegate, can sometimes slip past that static check and only fail at runtime with a confusing, low-level exception when the JIT actually tries to compile the closure.

🔎 The Problem

void Process(Span<char> buffer)
{
    // Won't compile - CS8175, span captured by the lambda
    // Action work = () => buffer[0] = 'x';

    // Fix: do the span-touching work BEFORE any delegate or async boundary,
    // then capture a plain copy of the value you actually need afterward.
    buffer[0] = 'x';
    int firstChar = buffer[0];

    Action logWork = () => Console.WriteLine($"First char was {firstChar}");
    logWork();
}

✅ Fix: Copy the Value Out Before You Capture Anything

  • Never try to capture a `Span<T>`/`ReadOnlySpan<T>` itself inside a lambda, a local function converted to a delegate, or an async/iterator method — do all span-touching work synchronously, inline, before any delegate or async boundary is crossed.
  • If you need a value FROM the span after that boundary, copy the specific data out into an ordinary non-ref-struct type — a char, an int, a string, or an array via `.ToArray()` — and capture that copy instead of the span.
  • Treat any compiler error mentioning “ref struct,” “ref local,” or CS8175 as non-negotiable rather than looking for a workaround to silence it — the handful of ways to technically bypass the check are exactly the paths that produce a runtime crash instead of a compile-time one.

🚨 Why This Is Dangerous

  • Because the whole point of the compiler’s restriction is to catch this at compile time, a case that slips past it and fails at runtime instead tends to do so with a confusing, low-level exception that gives no indication the actual root cause is a captured span.

A ref struct that escapes the compiler’s check doesn’t become safe to capture – it just fails somewhere less helpful.

— C# Best Practice

Related posts:

C# Value Types Cause Hidden Copies

C# Value Types Cause Hidden Copies

ConfigureAwait(false) — When It Actually Matters

ConfigureAwait(false) — When It Actually Matters

C#: Fix a Static Constructor That Never Runs Because the Type Is Only Ever Accessed Through an Abstr...

C#: Fix a Static Constructor That Never Runs Because the Type Is Only Ever Accessed Through an Abstr...

Views: 5

Post navigation

The AI Prompt That Converts a REST Endpoint Into a Typed SDK
Ajax: Fix a Cancelled Request Still Updating Stale UI State

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,059)
  • Get the User Name and Domain Name from an Email Address in SQL (983)
  • How to add default value for Entity Framework migrations for DateTime and Bool (981)
  • Get the First and Last Word from a String or Sentence in SQL (861)
  • How to select distinct rows in a datatable in C# (856)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (658)
  • Add Constraint to SQL Table to ensure email contains @ (613)
  • Average of all values in a column that are not zero in SQL (571)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (549)
  • Find numbers with more than two decimal places in SQL (477)

Recent Posts

  • Visual Studio: Fix Quick Actions Hiding Behind a Stale Squiggle
  • Photoshop: Fix a Smart Filter Resetting After You Relink It
  • Ajax: Fix a Cancelled Request Still Updating Stale UI State
  • C#: Fix a Span Captured by a Lambda Throwing at Runtime
  • The AI Prompt That Converts a REST Endpoint Into a Typed SDK
  • Git: Fix a Worktree Locking a Branch Needed Somewhere Else
  • Asp.Net Core: Fix a Background Service Leaking Scoped Dependencies
  • SQL Server: Fix a Columnstore Index Fragmenting After Bulk Deletes
  • Docker: Fix a Container Losing Logs After a Restart Policy
  • Asp.Net Core: Fix Output Caching Serving a Stale Authorized Page

Most Viewed Posts

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

Recent Posts

  • Visual Studio: Fix Quick Actions Hiding Behind a Stale Squiggle
  • Photoshop: Fix a Smart Filter Resetting After You Relink It
  • Ajax: Fix a Cancelled Request Still Updating Stale UI State
  • C#: Fix a Span Captured by a Lambda Throwing at Runtime
  • The AI Prompt That Converts a REST Endpoint Into a Typed SDK

Social

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