Skip to content

ref struct

Context: ref struct is a stack‑only struct that cannot be allocated on the heap. It is used for high‑performance scenarios (e.g., Span<T>).

public ref struct Buffer
{
private Span<byte> _data;
public Buffer(Span<byte> data) => _data = data;
public void Write(byte value) => _data[0] = value;
}
  • Cannot be boxed (no object conversion)
  • Cannot be used as a field in a class or non‑ref struct
  • Cannot implement interfaces
  • Cannot be used in async methods (cannot be captured by lambda/async state machine)

Zero‑allocation parsing: Use ref struct with Span<char> to parse CSV or JSON without allocating strings on the heap.

Example: System.Span<T> itself is a ref struct. Also Utf8JsonReader in System.Text.Json is a ref struct for high‑performance JSON parsing.