C# 7.2 introduced ref struct
s. However, given a ref struct
like this:
public ref struct Foo {
public int Bar;
}
I can
One can not use reference structures as type parameters because they cannot escape to a heap. There is no mechanism to tell the compiler that a method promises never to abuse the reference structure.
Beginning with C# 7.2, you can use the ref modifier in the declaration of a structure type. Instances of a ref struct type are allocated on the stack and can't escape to the managed heap. To ensure that, the compiler limits the usage of ref struct types as follows:
- A ref struct can't be the element type of an array.
- A ref struct can't be a declared type of a field of a class or a non-ref struct.
- A ref struct can't implement interfaces.
- A ref struct can't be boxed to System.ValueType or System.Object.
- A ref struct can't be a type argument.
- A ref struct variable can't be captured by a lambda expression or a local function.
- A ref struct variable can't be used in an async method. However, you can use ref struct variables in synchronous methods, for example, in those that return Task or Task.
- A ref struct variable can't be used in iterators.
More details from Microsoft about ref structs