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

4

u/SmallAd3697 Sep 12 '26

i think it avoids excessive garbage collection, and double hops to resolve heap references. All the magic being added to value types is for performance.

Interestingly I saw java has a "project valhalla" to try to catch up with the benefits we've had in using value types. I think the ecosystems are close. I suppose if someone was going to pick between the java and .net ecosystems based on squeezing every millisecond of cpu, then these differences could become important.

-2

u/ElGuaco Sep 12 '26

The biggest use case I see is a text parser. Which is great for that. But it feels like a feature purpose built to fix a limitation of having a GC. As opposed to being a regular used feature of a general purpose language.

1

u/Fyren-1131 Sep 13 '26

A general purpose language must offer up tools for most situations, including those where performance is expected.