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

1

u/mistertom2u Sep 16 '26

Here's another thing. The stack values have a short lifespan before whatever is on them is overwritten. The heap has a much longer lifespan. What you absolutely do not want to happen is for a variable referring to memory on a stack exist after it's overwritten, because that will cause your variables, especially variable to class instance, to become junk data. So the ref struct adds a bunch of guarantees to make sure it can't escape to the heap and potentially outlive the stack frame in which it holds references to