0
0
CsharpConceptIntermediate · 3 min read

What is ref struct in C#: Explanation and Example

A ref struct in C# is a special kind of structure that must always live on the stack and cannot be boxed or stored on the heap. It is used to ensure safe and efficient handling of stack-only data, like spans, by preventing the struct from being accidentally copied or stored in places that could cause memory issues.
⚙️

How It Works

A ref struct is a structure type that the C# compiler enforces to always stay on the stack. Think of the stack as a small, fast workspace where temporary data lives while your program runs. Unlike normal structs or classes, a ref struct cannot be moved to the heap, which is a larger, slower memory area used for long-lived objects.

This restriction helps avoid problems like memory leaks or unsafe access because the data is tightly controlled and cleaned up automatically when the method ends. You can imagine it like a sticky note you keep on your desk (stack) that you must throw away before leaving, rather than a note you put in a filing cabinet (heap) where it might get lost or forgotten.

Because of this, ref struct types cannot be boxed (converted to object), captured by lambdas, or stored in async methods, which all require heap allocation. This makes them ideal for working with sensitive or temporary data that needs to be very fast and safe.

💻

Example

This example shows a simple ref struct that holds a span of integers and calculates their sum. The ref struct ensures the span stays on the stack and is used safely.

csharp
using System;

ref struct IntSpanSum
{
    private Span<int> numbers;

    public IntSpanSum(Span<int> numbers)
    {
        this.numbers = numbers;
    }

    public int Sum()
    {
        int total = 0;
        foreach (var num in numbers)
        {
            total += num;
        }
        return total;
    }
}

class Program
{
    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5 };
        Span<int> span = array;
        IntSpanSum sumCalculator = new IntSpanSum(span);
        Console.WriteLine(sumCalculator.Sum());
    }
}
Output
15
🎯

When to Use

Use ref struct when you need to work with stack-only data that must not be copied or moved to the heap. This is common when handling Span<T> or similar types that provide fast, safe access to slices of memory.

Real-world uses include:

  • High-performance parsing or processing of data buffers.
  • Manipulating slices of arrays or strings without extra copying.
  • Writing low-level code that interacts with memory safely and efficiently.

Because ref struct types cannot be used in async methods or stored in fields of classes, they are best for short-lived, stack-bound operations.

Key Points

  • Stack-only: ref struct instances live only on the stack.
  • No boxing: They cannot be converted to object or stored on the heap.
  • Safe memory: Prevents unsafe memory access and improves performance.
  • Limitations: Cannot be used in async methods, lambdas, or as class fields.

Key Takeaways

ref struct types always live on the stack and cannot be boxed or stored on the heap.
They are ideal for working safely and efficiently with stack-only data like Span<T>.
You cannot use ref struct in async methods, lambdas, or as fields in classes.
Use ref struct to avoid copying and improve performance in short-lived operations.