What is ref struct in definition site

M.kazem Akhgary picture M.kazem Akhgary · Jan 12, 2018 · Viewed 7.2k times · Source

I think I've heard a term "ref like struct" in GitHub some time ago.

Now that I have my hands on latest C# version (7.3), I could finally test it my self. So this seems to be a valid code:

public ref struct MyStruct
{
    int x;
}

I know what are ref locals and ref returns as there is documentation about that. But I could not find documentation about ref struct.


Ref structs can not be used on auto properties or fields. They can not be cast to object either. These were empirical findings.

With "Span" background that new c# gave me recently I guessed that ref struct is a stack only struct. That is an struct that never goes on heap. But im not 100% sure.

Im pretty sure there should be a documentation about this but I failed to find it.

Answer

Ian H. picture Ian H. · Jan 12, 2018

After some research, I stumbled upon this article on Compile time enforcement of safety for ref-like types in C# 7.2.

This C# feature is also known as “interior pointer” or “ref-like types”. The proposal is to allow the compiler to require that certain types such as Span<T> only appear on the stack.

The site also states the benefits of doing so, mainly concerning garbage collection and stack allocation.


Using ref-like types also brings some restrictions with it such as:

  • ref-like type cannot be a type of an array element
  • ref-like type cannot be used as a generic type argument
  • ref-like variable cannot be boxed
  • ref-like type cannot be a field of ordinary not ref-like type
  • ref-like types cannot implement interfaces
  • indirect restrictions, such as disallowed use of ref-like types in async methods, which are really a result of disallowing ref-like typed fields.

This limits them to be used for parameters, local variables, and in some cases return values.


There also exists an official documentation from Microsoft, as @UnholySheep pointed out in the comments.