Course contentsShow
← C#
Lesson 65 of 1,9081. C# Language FoundationsFree lesson

Ref Struct Lifecycle Constraints

Design memory-safe code using restricted struct types that cannot escape the stack.

In this lesson, you will learn how to use ref struct types to force your data to live exclusively on the stack, ensuring high performance and absolute memory safety.

The Stack vs. The Heap

In C#, most objects live on the "heap," where the Garbage Collector (GC) manages them. However, sometimes you want to work with data that exists only for a fleeting moment—like a slice of an array or a temporary buffer—without triggering the GC. This is where the stack comes in. The stack is ultra-fast, but it is strictly "last-in, first-out."

What is a ref struct?

A ref struct is a special kind of struct that is forbidden from being stored on the heap. Because it can only exist on the stack, the compiler enforces strict rules to ensure it never "escapes" to a place where it might outlive its own validity.

Consider this example:

public ref struct TemporaryBuffer
{
    public Span<int> Data;
}

void Process()
{
    // This is valid: it lives on the stack and disappears when the method ends.
    TemporaryBuffer buffer = new TemporaryBuffer(); 
    
    // The compiler will throw an ERROR if you try to:
    // 1. Put this in a class or a field (heap memory).
    // 2. Use it in an async method (because async state machines are stored on the heap).
    // 3. Box it into an 'object'.
}

Why enforce these constraints?

If a ref struct were allowed to move to the heap, it could point to stack memory that no longer exists (a dangling pointer). By preventing these structs from being stored in classes or used in asynchronous methods, C# guarantees that the data inside a ref struct is always valid and never causes a memory leak.

These constraints act as a "safety harness." They allow you to write low-level, high-performance code—like working with memory buffers or Span<T>—while trusting the compiler to stop you if you accidentally try to store that data somewhere it doesn't belong.

Key Takeaway: ref struct types are restricted to the stack to guarantee memory safety, meaning they cannot be stored in classes, captured by async methods, or boxed as objects.