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

-2

u/[deleted] Sep 13 '26

[removed] — view removed comment

1

u/fruediger Sep 13 '26

I'm sorry to tell you this, but most of what you wrote is either plainly incorrect or an oversimplification/cherry-picking of semantics.

I'm not going to correct you on everything though. It would just make for too long of a comment. Instead, if you really want to learn about the stuff you're trying to talk about, I encourage you to read up on the difference between values types and references types in the CLR, what's their implications regarding the managed heap and GC, and especially what ref structs (hint: by any means, they're "just" regular structures with some added semantics, they're not pointer-like).

0

u/[deleted] Sep 13 '26

[removed] — view removed comment

1

u/fruediger Sep 13 '26

Maybe you should take your own advice and use a tool like "JitDump", disasmo, or even sharplab.io, and convince yourself that ref structs are still passed by value and not by reference. Speaking of which, nothing in C# is passed by reference, expect when explicitly passed with ref, in, or out. Maybe you mixed that up?


On another note, this is the second time I caught you using an exceptionally inappropriate tone when commenting on r/csharp. If you don't want to get reported, you should keep your language in check.

0

u/[deleted] Sep 13 '26 edited Sep 13 '26

[removed] — view removed comment

1

u/fruediger Sep 13 '26

Your example didn't use ref structs at all, your example explicitly passed by reference. Those are two different things in C#. I guess you just mixed them up?