C# ref struct: Constraints and Practical Use
Learn how C# ref struct types enforce stack-only allocation, what compiler restrictions they carry, and how Span<T> uses them for safe, allocation-free memory access.

ref struct is a C# value type that the compiler restricts to stack-only usage. The restriction exists to support types like Span<T> that reference contiguous memory without introducing heap allocations or boxing. This article explains the constraint, shows how to declare a ref struct, and covers where instances are allowed and when you should use them.
The Core Constraint: Stack-Only Allocation
The defining rule of a ref struct is that instances can only live on the stack. The compiler enforces this by rejecting usages that would allow the value to reach the managed heap: boxing, storing it as a field in a class, using it as an array element, passing it as a type argument to a generic type that does not opt in to ref struct type arguments, or keeping it across an await in an async state machine. The rationale is that a ref struct often holds a pointer to memory that must remain valid only for the duration of the current stack frame. Allowing it to escape to the heap would make lifetime validation impossible.
This stack-only behavior is not a performance hint; it is a hard language rule. If you try to box a ref struct or pass it to a generic collection such as List<T>, the compiler produces an error. The restriction is what makes types like Span<T> safe and efficient: they can point to stack memory, unmanaged memory, or managed arrays without risking a dangling reference.
Declaring a ref struct
You declare a ref struct with the ref modifier on the struct keyword:
public ref struct BufferReader
{
private ReadOnlySpan<byte> _buffer;
private int _position;
public BufferReader(ReadOnlySpan<byte> buffer)
{
_buffer = buffer;
_position = 0;
}
public byte ReadByte()
{
return _buffer[_position++];
}
}This BufferReader is a ref struct because it contains a ReadOnlySpan<byte> field. Since ReadOnlySpan<T> is itself a ref struct, any struct that holds it must also be a ref struct. The compiler enforces this transitively, so you cannot hide a ref struct inside a regular class or struct.
Where ref structs Are Allowed
ref struct instances can be used as local variables, method parameters, return values, and ref or in arguments. They can also be stored in other ref struct types. For example, you can pass a Span<T> to a method that accepts a ReadOnlySpan<T>, and you can return a Span<T> from a method as long as the underlying memory is still valid. This is common when working with stack-allocated buffers or slices of arrays.
public static Span<int> GetSlice(int[] array, int start, int length)
{
return array.AsSpan(start, length);
}The returned Span<int> is safe because the array is managed by the garbage collector, and the span carries a reference to the array. For stack-allocated memory, you must ensure the span does not outlive the stack frame that owns the memory.
Span<T> and Memory<T>: The Primary Use Case
The most important ref struct in the .NET ecosystem is Span<T>. It provides a type-safe view over contiguous memory, whether the underlying memory is an array, a string, unmanaged memory, or a stack-allocated buffer. Because Span<T> is a ref struct, it cannot be stored in a field of a class, and older C# versions also prohibited it in async methods. That limitation is intentional: Span<T> is designed for synchronous, short-lived operations where performance matters.
Memory<T> is the companion type that does not carry the ref struct restriction. You can store Memory<T> in a class, use it in async methods, or pass it to lambdas. The tradeoff is that Memory<T> may allocate when it wraps non-array memory, while creating a Span<T> from an existing array, string, or stack buffer does not. Use Span<T> for synchronous processing and Memory<T> when you need to store the reference beyond the current call stack.
Performance and Allocation Behavior
The primary performance benefit of a ref struct is avoiding heap allocations and boxing. When you use Span<T> to slice an array, no new array is allocated; the span points to the original memory. This is critical in high-throughput code paths such as parsers, serializers, and network protocol handlers, where fewer allocations reduce garbage collection pressure.
Because ref struct types cannot be boxed, they do not incur an object header or finalizer. They are stack values, and the JIT can often keep them in registers. The same restriction means a ref struct cannot be used in contexts that require an object, such as calling object.Equals, GetHashCode, or using string interpolation. If you need those operations, implement them as methods or interfaces on the ref struct.
ref struct does not automatically make your code faster. The benefit comes from avoiding allocations and enabling compiler optimizations such as inlining and scalar replacement. If you copy a large ref struct repeatedly or use it in a way that forces it to be stored in memory, you may not see a benefit. Measure your specific scenario before assuming ref struct will improve performance.
Common Pitfalls and Compiler Errors
The compiler is strict about ref struct usage, and you will encounter errors when you try to violate the rules. A common mistake is attempting to use a ref struct as a type argument for a generic type that does not opt in:
List<Span<int>> list = new(); // Error: Span<int> cannot be used as type argumentThe compiler rejects this because the generic type could store the value in a heap-allocated field. Starting with C# 13, a generic parameter can explicitly opt in to ref struct type arguments with an allows ref struct anti-constraint; List<T> does not use that opt-in, so this example remains invalid.
A ref struct cannot cross an await boundary in an async method. Starting with C# 13, a ref struct can appear in an async method only if it does not live across an await; older compilers rejected the use entirely. If you need to process data after an await point, copy it into a Memory<T> or a regular array first.
Another pitfall is capturing a ref struct in a lambda or a local function that is converted to a delegate. The delegate is a heap object, so the compiler disallows the capture. You can pass a ref struct as an argument to a local function that is called directly and never converted to a delegate, as long as the value does not escape the current stack frame.
When to Use and When to Avoid
Use a ref struct when you need a lightweight, allocation-free view over contiguous memory and the lifetime is strictly bounded to the current method call. This is common in parsing, binary reading, and low-level data manipulation. If you need to store the data structure in a field of a class, pass it across an await, or use it in a generic collection, use a regular struct, a class, or Memory<T> instead.
Avoid ref struct for simple data containers that do not reference external memory. A regular struct is easier to work with and does not carry the same restrictions. Also avoid creating a ref struct that holds a reference to managed memory if you do not need the stack-only guarantee; the restriction will limit your API design without providing a clear benefit.
Interop and Advanced Scenarios
ref struct is particularly useful when working with unmanaged memory or stack-allocated buffers. You can use stackalloc to create a buffer on the stack and then wrap it in a Span<T>:
Span<byte> buffer = stackalloc byte[256];
FillBuffer(buffer);The stackalloc expression returns a Span<T>, which is a ref struct. This pattern is common in high-performance code where allocating a small buffer on the heap would be wasteful. The compiler ensures that the Span<T> does not escape the stack frame, so the memory is automatically reclaimed when the method returns.
When interoperating with native code, you can use Span<T> to represent a contiguous block of memory without pinning a managed object if the memory is not owned by the garbage collector. For example, you can create a Span<T> from a byte* that points to unmanaged memory and pass it to a method that expects a ReadOnlySpan<T>. If the pointer points into a managed heap object, pin that object first. The span carries a length, and runtime bounds checks help prevent out-of-range access.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.