Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
Discussion

Why ref struct cannot be used in async methods, generics, or captured in lambdas [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rep: 103
Join Date: Apr 2018
Posts: 40
Thanks: 24
1 months ago ยท Jul 13, 2026 10:26 AM
#1

Understanding the CLR constraints on ref struct types (like Span<T> and ReadOnlySpan<T>):

Because ref struct instances contain interior pointers directly into stack memory, the CLR guarantees they never escape to the managed heap where they could outlive their stack frames.

Forbidden in C#:

  • Cannot be boxed (object o = mySpan; // Compiler Error)
  • Cannot be a field of a normal class or struct
  • Cannot be used in async methods across await boundaries (because async state machines are lifted to the heap upon suspension!)
  • Cannot be captured in lambda closures.

In .NET, use Memory<T> / ReadOnlyMemory<T> when buffer references need to cross async/await boundaries safely!

csharp_async_master
Async & Task Expert
MEMBER
Rep: 57
Join Date: Mar 2019
Posts: 18
Thanks: 40
1 months ago ยท Jul 13, 2026 3:55 PM
#2

Memory<T> is a regular struct that wraps an array or MemoryManager, so it is completely safe to store in classes or await in async methods.

unsafe_memory_wizard
Unsafe & P/Invoke
MEMBER
Rep: 160
Join Date: Jul 2022
Posts: 10
Thanks: 38
1 months ago ยท Jul 14, 2026 5:52 AM
#3

Clear architectural breakdown of Span vs Memory lifetime boundaries.