When to Use C#9 Records [closed]
Asked Answered
C

0

7

C#9 was officially announced a couple days ago, and one of the biggest additions to the language is the new "record" type using the data keyword. This new feature feels very similar to the readonly structs of C#7.2, so I'm confused why one would use one over the other. Specifically:

  1. Why would one use a data struct over a readonly struct? Are these not exactly the same thing?
  2. Can one declare a data readonly struct? Wouldn't that be redundant?
  3. Why would one use a data class over a readonly struct? They both achieve immutability and value-type equality, so is it just a question of performance (heap allocation vs copying when passed as a parameter)?

Bonus points: I could use some help understanding why "records change the defaults of what a simple member declaration...means"? I've been around enough enterprise code to anticipate giant data classes with dozens of members, where an inexperienced programmer will see string FirstName; and not think to scroll up to look for a data keyword, assuming that its a private field, not a publicly accessible property!

Ceremonious answered 21/5, 2020 at 16:54 Comment(6)
As far as #3 goes, a data class supports inheritance where a readonly struct does not. If data classes have similar perf behavior and are stack allocated like structs, but having inheritance then I want them to have strongly typed variants of structs (think vectors in different reference frames).Morn
Why not make structs inheritable instead of adding entire new denizen to the language? I also want to know developers' opinions, so maybe the OP should paste this onto Reddit seeing that StackOverflow doesn't want to allow this question?Polymeric
#1: Yeah, let's ignore all the new syntax that ONLY applies to data records ;)Abnegate
Until they actually release C# 9 I wouldn't take any "announcement" as anything other than "we hope to". They "announced" a lot of things for both C# 7 and 8 that were never released either, some of them are in this C# 9 "announcement". So forgive me for not holding my breath.Fumikofumitory
@Morn Good point about inheritance. My guess is that records will not be stack-allocated, because they are classes, but then I have no idea for sure. Hopefully MS will provide some guidance on which declaration should be the preferred "default" for immutable data, kinda like how they recommended classes over structs back in the day.Ceremonious
Have look on my answer hereContusion

© 2022 - 2024 — McMap. All rights reserved.