Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use record struct instead of struct, and vice versa?

I have found out recently about the record keyword in C#, and saw that it can be used as record struct in a way to make it, if I understood correctly, a value type instead of a reference type.

However, I'm having a hard time to understand when exactly to use record struct instead of just the struct. From what I saw, the record struct has some base implementations that the struct doesn't (like the == and != operators, an override of the ToString, and some other things), but is it all that is there for difference between the two? If not, what needs to be considered when deciding to use one or another?

From the way I currently see, it might be better to always use the record struct just to take advantage of those implementations that already comes with it.

like image 481
mpatrickaires Avatar asked Dec 17 '25 22:12

mpatrickaires


1 Answers

This answer assumes:

  • It is known what the record keyword does in c#;
  • It is known what a struct is how it is different from class;

Then, the decision of using struct instead of record struct comes down to:

  1. You don't need the default implementation that record bakes in.

    Maybe your struct is so short-lived that it will be used only to pass around structured data; it will be created, consumed and be disposed in very well-known places and you are in total control of their usage. If you are totally, completely sure that you don't need equality comparison, pattern matching or string representation, than you could avoid a few bits of meta-data in your assembly and a few lines of documentation.

  2. You don't want the default implementation that record bakes in.

    This point is kinda weak, considering that you can declare your type as record struct and still provide a custom implementation of any of the automatic behavior. You can even specify attributes to the auto-properties with the concise syntax. So unless you are planning to provide a custom implementation to most of the automatic ones, you would still benefit from using record.

  3. You can't use record struct because you are locked in a .net version that doesn't support c#10.

    Well, not much to say in this case.


In summary, record struct is just better in the general case, and honestly it is what struct should have been by default since it's inception.

like image 153
Rodrigo Rodrigues Avatar answered Dec 20 '25 11:12

Rodrigo Rodrigues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!