Search code examples
c#.netstructc#-7.3ref-struct

Why can I declare a ref struct as a member of a class in c#7.3?


According the docs:

You can't declare a ref struct as a member of a class or a normal struct.

But I managed to compile and run this:

public ref struct RefStruct
{
    public int value;
}
public class MyClass
{
    public RefStruct Item => default;
}    
...       

MyClass c = new MyClass();
Console.WriteLine(c.Item.value);

Now RefStruct is a ref struct and it is a member of a class. Is this statement wrong in some cases?

UPDATE Now the docs have been updated to a more precise description.


Solution

  • It is not field of your class but rather return value of a property getter - which is fine as it is just function return value.

    Note that "as a member of a class" usually includes properties and probably should be changed to "field of a class".

    If you would try to declare it as a class field (either directly or indirectly via auto-implemented property) this will require part of the class (the data for ref struct) to be allocated on the stack and the rest allocated in manged heap.

    The code in the question defines non-autoimplemented property. As result there is no need for compiler to automatically create hidden field of the property type in the class. So while property result type is ref struct it actually is not stored in the class and hence does not violate requirement for this ref struct type not be included into any class. Note that even making setter method would be fine by itself - storing value for that property would be tricky, but you can safely store content of the ref struct (public int value; as in the post) in set and recreate it in get.