Why ref structs cannot be used as type arguments?

3.7k views Asked by At

C# 7.2 introduced ref structs. However, given a ref struct like this:

public ref struct Foo {
  public int Bar;
}

I cannot use it as a type argument:

int i = 0;
var x = Unsafe.As<int, Foo>(ref i); // <- Error CS0306 The type 'Foo' may not be used as a type argument.

I understand that ref structs can only exist on the stack, and not the heap. But what if the generic method that would use such ref structs is guaranteed to never put them on the heap, as in the example above that uses System.Runtime.CompilerServices.Unsafe package? Why can I not use them in those cases as type parameters?

1

There are 1 answers

0
Display name On

The primary guarantee made by a ref struct is that it will never escape to the heap.

In a generic method, the compiler doesn't validate the no-heap guarantee (since almost all types can exist on the heap). The most straightforward way to prevent generic methods from leaking ref structs is to simply forbid the use of a ref struct as a type parameter, so that's what C# does.

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