ref Structs
Instances of a ref struct are allocated on the stack and cannot escape to the managed heap.
Restrictions:
- A
refstruct cannot implement interfaces - A
refstruct cannot be a type argument - A
refstruct variable cannot be captured via lambda expression or local function - A
refstruct variable cannot be used in an async method (but can be used in a synchronous method that returnTask/Task<T>)
disposable
A ref struct can be made disposable: create an instance or extension Dispose method that is accessible, parameterless, and returns void.
ref Fields
ℹ️ Important
Availability: C# 11
⚠️ May hold null. Use
Unsafe.IsNullRef<T>(T)to determine if a ref field is null.
ref readonly
The readonly modifier affects the expression to its right:
ref readonly int someVar; // someVar cannot receive a new value.
readonly ref int someVar; // someVar cannot refer to another object.
readonly ref readonly int someVar; // someVar cannot receive a new value and cannot receive refer to another object.
scoped ref
ℹ️ Important
Availability: C# 11
Adding the scoped modifier asserts that code will not extend the lifetime of a variable.