C# Reference ยท Keywords and Statements
ref struct and ref locals
Reference for C# ref struct, ref locals and ref returns: stack-only types, Span<T>, restrictions, escape rules, ref fields, scoped and allows ref struct.
A ref struct is a value type that the compiler guarantees will live only on the stack. It can never be boxed, stored in a field of a class, captured by a lambda, or kept across an await. In exchange it may hold references to other memory (a ref field), which is how Span<T> and ReadOnlySpan<T> point at arrays, stack buffers, or native memory without copying.
ref locals and ref returns are the related feature for ordinary code: a local variable or a method result that is an alias to another variable, so writing to it changes the original.
ref struct Cursor { public Span<int> Window; } ref int first = ref numbers[0]; first = 100; // numbers[0] is now 100
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
[modifiers] ref struct Name { ... } readonly ref struct Name { ... } ref struct Name : IDisposable { ... } // may implement interfaces ref T local = ref expression; ref readonly T local = ref expression; ref T Method(...) { return ref expression; } ref T field; // inside a ref struct (C# 11) scoped ref T parameter // C# 11 lifetime annotation where T : allows ref struct // C# 13 anti-constraint
| Part | Description |
|---|---|
ref struct |
Declares a stack-only type. May contain ref fields, but must be a struct. |
ref local |
An alias for a variable, field or array element. Must be initialized with = ref x. |
ref return |
Returns an alias. The referenced variable must outlive the method (a field, array element, or ref parameter, never an ordinary local). |
ref reassignment |
local = ref other; makes an existing ref local point somewhere else. |
allows ref struct |
Lets a generic type parameter be instantiated with a ref struct (used by Span-friendly APIs). |
Errors: returning a reference to an ordinary local variable is CS8168; boxing a ref struct is CS0029 (no conversion to object); a class field of a ref struct type is CS8345; using one as an ordinary generic argument, as in List<Window>, is CS9244.
Usage notes
- Why the limits. The stack-only guarantee is what makes it safe to point at stack memory from
Span<T>. If a span could live on the heap, it could outlive the buffer it points to. - Interfaces. A ref struct can implement an interface, but cannot be converted to it (that would box). It works as a generic argument only for parameters declared
allows ref struct. - Disposal. A ref struct with a public
Dispose()method can be used inusingeven if it implements no interface (pattern-based disposal). - foreach. Ref structs are common as enumerators, for example the type returned by
GetEnumerator()of a span. - readonly ref struct makes all fields read-only and lets the compiler avoid defensive copies.
- Escape analysis. The compiler tracks where a reference could end up (ref-safe-context and safe-context).
scopedon a parameter or local tells it that a reference does not escape the method, so more calls compile. - Async and iterators. Since C# 13 a ref struct variable can be declared inside an async method or iterator as long as it is not live across an
awaitoryield. - Common mistake. Trying to store a
Span<T>in a class field or in a lambda. UseMemory<T>for that, and call.Spanlocally. - Ref returns and thread safety. A ref return is a live alias; if the array or list is resized in between, the alias still refers to the old storage (for
List<T>useCollectionsMarshal.AsSpancarefully).
Related
- ref, out and in
- struct
- readonly
- Tutorial: Spans and Memory, Unsafe code