Member-only story

Use reference type in the struct in .NET

Guriy Samarin
2 min readJul 6, 2021

--

I’m not used to writing general texts. I’m more like the HowTo kind of guy. But the matter of using reference type inside the struct got me confused. And I decided to blog about it. It’s obvious that struct plays a different role in the .NET ecosystem than it was designed to. And we have readonly and ref structs to prove it. But let’s leave historical reasons aside and try to discuss struct as a newly created type (as record f.i.).

First of all — the struct feels like an optimization point and compatibility instrument, not a full-blown data type. Hints to this are in the recommendation on how do you need to use them

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

In related types like ValueTask (which you shouldn’t use unless you 100% sure) and in any await state machine implemented by class in Debug and by struct in Release.

Ability to set struct layouts for interoperability (blittable types and so on). Yes, I know that Arrays are classes and they can be blittable too (and there are still some classes that could be marshaled as formatted type). But If you wrote any code to deal with the C++ library, I’m pretty sure structs were the main type of communication.

--

--

Guriy Samarin
Guriy Samarin

Written by Guriy Samarin

Software developer at Amazon. Web (mostly backend) development now. My stack — .NET (APS.NET Core MVC).

No responses yet