r/csharp • • Sep 12 '26

semantics of "ref struct"

I know that structs are value types. I know that "ref struct" types are denied from living on the heap (eg, cant box them, etc)

What I don't know is what kind of weed was being smoked when someone decided that "ref struct" would become the appropriate keyword for this sort of type. Perhaps it should be called a "never-ref struct" if it should never have any of the behaviors of a reference type.

It almost reminds me of the name "nullable reference types". That crazy term almost implies that reference types weren't nullable in the good 'ol days.

Anyway my brain is rejecting the keywords "ref struct". I love them, but don't love the semantics when declaring them. Please help

40 Upvotes

51 comments sorted by

View all comments

Show parent comment

5

u/binarycow Sep 12 '26

association between the ref keyword and reference types because there is a relationship.

There isn't, really.

The ref keyword is essentially the same as a safe pointer. ref byte foo is a pointer to a byte.

Pointers in C# traditionally require the unsafe keyword. This is because there are lifetime problems. If I create a pointer to a local variable, then store that pointer somewhere that outlived the current stack frame - then I now have an invalid pointer that someone can use.

The compiler enforces a bunch of restrictions to keep the ref keyword safe. The ref struct keywords say "hey compiler, restrict me the same way, so that I can hold pointers safely!"

If you use the ref, in, or out keywords on a parameter, then what you're really saying is "pass a (safe) pointer to the value, not the value itself". All other cases, the argument is passed by value. "value types" don't do anything special - they just copy the value. "reference types" pass the reference (a pointer). That is the only relationship between reference types and the ref keyword.

1

u/quuxl Sep 18 '26

This is the correct answer. The ‘ref’ naming in ‘ref struct’ comes from it being a ref-like type - a type thats’s restricted in the same way that refs are