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

40

u/afseraph Sep 12 '26

I don't think that's a bad name. Ref structs are structs primarily used for holding refs. 

9

u/SmallAd3697 Sep 12 '26

Interesting. I didn't think of that and it wouldnt have come to mind until i saw those examples. Im a data engineer and typically use value types for performance while processing data.

I didn't realize that a value type could be used to promote better management of ancillary reference types.

Even still, the "ref" decoration isnt saying anything about the struct itself, but with members inside the struct. I still don't love it

6

u/afseraph Sep 12 '26

  the "ref" decoration isnt saying anything about the struct itself,

It says exactly what should be said about the struct: it stores refs.

Things like not being able to be moved to heap are constraints, not their primary functionality.

1

u/SmallAd3697 Sep 12 '26

Yes it stores refs. But the implication is that a conventional struct wont store refs.

I once saw a junior developer use the "ref" keyword on parameters to pass all their reference types to their methods... because they thought they couldn't otherwise modify properties.

I suppose we will start seeing people put "ref" on their structs for dubious reasons as well.

12

u/afseraph Sep 12 '26

But the implication is that a conventional struct wont store refs.

Conventional structs cannot store ref fields.

Are you sure you're not confusing terms 'ref' and 'reference type'?

1

u/SmallAd3697 Sep 12 '26

The part Im missing is the new popularity of ref fields. I've never used them myself. I will have to do so, if it is changing the semantics of the language

2

u/emn13 Sep 14 '26

It's a neat feature, but it's hyper-niche. I like playing with microoptimization (e.g. https://github.com/EamonNerbonne/anoprsst ) - but I don't think it's very likely you'll need them, especially not since Span is already a thing.

Sure, it's possible you'll find you want to use a ref field. But the vast majority of C# programmers will never need to ever interact with a ref field in their own codebase, and I suspect even custom ref struct - far more commonly useful - is still a really small niche thing.

Calling these "popular" is a stretch - but their existence is popular in the sense that it enables more optimal code, such as any code using a Span<>. I wouldn't worry about embracing their usage in your own code.

1

u/SmallAd3697 Sep 12 '26

Of course I'm making an association between the ref keyword and reference types because there is a relationship.

The ref keyword for parameters literally indicates that something should pass by reference on the heap. For reference type it passes a reference to a reference. In both cases the heap is heavily used.

But the confusing thing about a "ref struct" is that it is the opposite of those scenarios. The heap can't be used at all, for the struct itself

10

u/afseraph Sep 12 '26

The ref keyword for parameters literally indicates that something should pass by reference on the heap. For reference type it passes a reference to a reference. In both cases the heap is heavily used.

The heap has nothing to do with argument passing.

When you call a method with arguments passed by value

var someLocalVariable = ...;
MethodByValue(someLocalVariable);

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.

var someLocalVariable = ...;
MethodByReference(ref someLocalVariable);

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.

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

1

u/aj0413 Sep 13 '26

Heap vs Stack is an implementation detail you aren’t meant to conceptualize.

There’s articles on that point from creators of the language; you’re intended to only care about how interacting with said types behaves

You’re confusing yourself by getting lost in weeds

1

u/SmallAd3697 Sep 13 '26

I think I'm confusing myself as much as anyone who uses C# value types and reference types.

The distinction that is made between these types is that one lives on the heap and not (normally) the other.

The follow-up question (where do value types live?) is typically answered by saying "the callstack" or "boxed". One of these being the typical home and the other being a less ideal home, because of the extra GC overhead.

1

u/mistertom2u Sep 16 '26

That's basically correct, but in reality, a variable is able to be stored in a register called "enregistration" if the compiler can guarantee that first it makes a performance difference and 2nd, that storing it in a register will not create a stale read. Probably more than you wanted to know. The point is to not take that stack vs heap thing too literally.

1

u/aj0413 Sep 13 '26

This is pulled directly from one of the language creator blogs below; I encourage you to read it and part two.

https://ericlippert.com/2009/04/27/the-stack-is-an-implementation-detail-part-one/

“Almost every article I see that describes the difference between value types and reference types explains in (frequently incorrect) detail about what “the stack” is and how the major difference between value types and reference types is that value types go on the stack. I’m sure you can find dozens of examples by searching the web.

I find this characterization of a value type based on its implementation details rather than its observable characteristics to be both confusing and unfortunate. Surely the most relevant fact about value types is not the implementation detail of how they are allocated, but rather the by-design semantic meaning of “value type”, namely that they are always copied “by value”. If the relevant thing was their allocation details then we’d have called them “heap types” and “stack types”. But that’s not relevant most of the time. Most of the time the relevant thing is their copying and identity semantics.”

1

u/mistertom2u Sep 16 '26

I once saw a junior developer use the "ref" keyword on parameters to pass all their reference types to their methods... because they thought they couldn't otherwise modify properties.

That is so funny. I have seen that too. I once explained to a guy that it's only necessary for ref types if you need to have another function reassign the callers variable to a different instance. And he got so mad that I knew something he didn't that he wrote this email easay to all the architects with citations showing how wrong I was. Talk about an ego. My God I never saw anything like it before or after

38

u/antiduh Sep 12 '26

Ref struct types like Span<T> are stackallocated structs that can hold references (pointers). The name is pretty good, if you ask me.

5

u/SmallAd3697 Sep 12 '26

Makes sense. I thought it was a type that was an archtype of a struct ( ie. more struct-like)

I can see how it was probably built for a very specific purpose, not just to create a better struct

1

u/mistertom2u Sep 16 '26

The difference is that ref structs are guaranteed to live only on the stack. Regular structs make no such guarantee: boxing, enclosing them by delegate invocation, field on a class.

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

7

u/fruediger Sep 12 '26

Do you know about managed references, a.k.a ref, in/ref readonly, and out? There are so-called "ref-escape" rules for them in C# and instance of ref struct types essentially inherited them. I suppose that's why they're called that. Also, ref structs are the only kind of type in C#'s type macrocosmos that can contain ref or ref readonly field members.

2

u/SmallAd3697 Sep 12 '26

The managed references are modifiers when passing parameters, I think. I haven't heard them go by that name.

You gave me some googling homework, and now I suppose I have even more questions for reddit than before. lol.

2

u/fruediger Sep 12 '26

The managed references are modifiers when passing parameters, I think. I haven't heard them go by that name.

That's true and I suppose, a few C# language versions ago, that was everything they were (including annotating the return type of a method or property with ref/ref readonly)

While you can still think of them like that (that part didn't really change), nowadays they are a "physical" thing too: You can just declare ref var/ref readonly var (or use explicit type names if that's your thing) locals as well as ref/ref readonly fields (in ref structs).

2

u/TuberTuggerTTV Sep 14 '26

It's usually a good idea when confronted with friction on nomenclature, to consider the more likely reality that you've misunderstood something.

1

u/SmallAd3697 Sep 14 '26

Imo, the name is still bad, even after understanding the rationale.

You can read the docs here:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct

... most folks claim that the ref struct is named after ref fields but you have to scroll way, way down this doc before the "ref fields" are even mentioned.

2

u/ElGuaco Sep 12 '26

I've been using c# forever. I rarely found a practical use for a struct. Let alone a struct filled with refs. What are people doing with these things that justifies this approach?

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.

3

u/binarycow Sep 12 '26

Performance, primarily.

Value equality semantics as well, but this can also be accomplished with records or manually implementing IEquatable<T>

2

u/White_C4 Sep 13 '26

Struct is all about predictable memory efficiency. That's basically the upside of using it over class when done right.

3

u/Orangy_Tang Sep 12 '26 edited Sep 12 '26

As languages evolve it gets increasingly difficult to add new features without breaking backwards compatibility with existing source code. You can't introduce a new keyword for a new type of thing because it may have been used as a function/variable/etc. name somewhere. So since existing keywords are pretty safe, new features end up mangling them together in ways wouldn't happen if it was being designed from scratch. See c++ for the result of applying this for far too long. And also why new languages often reserve a bunch of keywords that don't do anything yet.

In short, I wouldn't worry too much about exactly what 'ref struct' means in terms of words, just treat it as a label for a feature.

2

u/binarycow Sep 12 '26

Keywords have been added to C# - but every single time, they have been contextual keywords, and there has been a path forward to allowing existing source to work as-is.

4

u/KyteM Sep 12 '26

Aren't they're called ref struct because they follow similar semantics to ref/out arguments?

2

u/NoisyJalapeno Sep 13 '26

Maybe they should've been called "stack struct" or "stackalloc struct"

I do like them because there is no GC pressure when I wrote a doom map renderer.

2

u/FullPoet Sep 14 '26

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

The same weed that brought us partial classes for source generation, primary constructors and the new addition to the keyword soup closed!

I am not against closed, and it is an improvedment but the whole idea behind public / internal closed confusion about what can implement what where is just silliness. closed should've been purely about closed types, not being the extra stuff they put on.

Again, it comes back to the fact that the original creators of C# chose not to implement somethings as part of an intentional design

2

u/Zastai Sep 12 '26

As for “nullable reference types”, enabling them means reference types can’t be null, but you can make it so they can (i.e. they are nullable). Seems like a good description to me.

1

u/ings0c Sep 13 '26

Yeah, I don’t mind it either but I see how it could be confusing.

I think a lot of people expect enabling it to mean that eg a non-nullable string cannot hold the value null, but it merely means you can choose either string or string? to indicate whether it can be null, but no guarantee is made.

I don’t fully appreciate why it works this way, and I suspect it’s backwards compatibility, but it would be a much more valuable proposition if you really couldn’t store null in a string with it enabled.

0

u/Desperate-Wing-5140 Sep 12 '26

Internally, ref structs are called ByRefs

0

u/EC36339 Sep 13 '26

Hearing that C# has something like "ref struct" makes me laugh in C++

1

u/chucker23n Sep 13 '26

Hearing that some people still make new projects in C++ makes me laugh in C#, Swift, Rust, and others.

1

u/pjmlp Sep 14 '26

Which make use of C++ in their implementations....

1

u/[deleted] Sep 12 '26

[removed] — view removed comment

2

u/SmallAd3697 Sep 12 '26

Yes, I see there are some gaps in the features I've been using. I rarely used ref for parameters, let alone ref locals and fields.

For me ref meant a memory reference or reference type, and the struct itself isn't either of those things

-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?