ref-struct

Why ref structs cannot be used as type arguments?

随声附和 提交于 2020-05-25 06:40:42
问题 C# 7.2 introduced ref struct s. 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

Why ref structs cannot be used as type arguments?

╄→尐↘猪︶ㄣ 提交于 2020-05-25 06:40:29
问题 C# 7.2 introduced ref struct s. 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