Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

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

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix a Ref Struct Escaping Scope Through a Local Function

- 24.11.26 - ErcanOPAK

🔧 C#: Fix a Ref Struct Escaping Scope Through a Local Function

A ref struct like Span<T> is restricted by the compiler specifically to prevent it from outliving the stack frame that created it, since it may wrap memory such as a stackalloc buffer that isn’t valid once that frame unwinds. A local function declared inside the same method is still compiled as logically part of that method for most purposes, but the moment it’s converted to a delegate, passed where an Action is expected, stored in a variable, or captured by an async state machine, the compiler has to move its captured variables onto the heap to survive past the original call, and that is exactly the conversion a ref struct capture must be rejected for.

🔎 The Problem

void ProcessChunk(Span<byte> buffer)
{
    void LocalWrite() => Console.WriteLine(buffer.Length);
    // Fine as long as LocalWrite is only ever called directly -
    // the compiler keeps the ref struct capture on the stack.
    // The moment this local function is converted to a delegate
    // (Action action = LocalWrite;) the compiler must reject it,
    // since a heap-allocated delegate cannot safely carry a
    // stack-only Span capture past the current frame's lifetime
    LocalWrite();
}

✅ Fix: Keep the Capture Out of Reach of a Delegate

  • Pass the ref struct’s needed data, such as its length or a computed value, as an ordinary parameter into the local function instead of capturing the ref struct itself by closure, so converting the function to a delegate is never even possible to get wrong.
  • If the local function genuinely needs the whole span, keep it strictly non-capturing of outer ref struct state and call it only directly, never storing it in a variable or passing it where a delegate type is expected.
  • Enable the project’s ref-safety analyzers and treat any warning about a ref struct capture as a hard build error, since this entire class of bug is exactly what those specific compiler diagnostics exist to catch early.

🚨 Why This Is Dangerous

  • A Span capture that genuinely escapes its valid stack lifetime through a delegate conversion is undefined behavior, not just a style issue, and failures from it tend to show up as sporadic data corruption or crashes that are extremely difficult to reproduce reliably.

A ref struct’s whole safety model is never let me outlive my frame — a local function that quietly becomes a delegate is one of the few ways a program can still try to break that promise.

— C# Best Practice

Related posts:

C# Static Constructors Break Startup

C# Static Constructors Break Startup

C#: Use Static Members for Class-Level Data

C#: Use Static Members for Class-Level Data

C#: Fix the Boxing Allocation Hiding Inside Every Interface Call on a Struct

C#: Fix the Boxing Allocation Hiding Inside Every Interface Call on a Struct

Views: 7
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

C#: Fix a Pattern Match Ignoring a Custom Deconstruct Order
Kubernetes: Fix a StatefulSet Stuck Because Its PVC Won’t Resize

Leave a Reply Cancel reply

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

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 629 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

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

Social

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