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?
The primary guarantee made by a
ref structis 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 aref structas a type parameter, so that's what C# does.More details from Microsoft about ref structs