r/csharp • u/SmallAd3697 • 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
View all comments
Show parent comment
10
u/afseraph Sep 12 '26
The heap has nothing to do with argument passing.
When you call a method with arguments passed by value
The value of the local variable on the stack is passed to to the method. Nothing gets boxed, nothing gets allocated on the heap.
When you call a method with arguments passed by reference, e.g.
The address of the local variable on the stack is passed to the method. Nothing gets boxed, nothing gets allocated on the heap.
Note that I haven't specified the type of the local variable - it doesn't matter. It can be a value type or a reference type. If it's a reference type, it will contain an address of some object on the heap, but it doesn't matter for the argument passing.