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:
- Why would one use a
data struct
over areadonly struct
? Are these not exactly the same thing? - Can one declare a
data readonly struct
? Wouldn't that be redundant? - Why would one use a
data class
over areadonly 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!
data class
supports inheritance where areadonly struct
does not. Ifdata class
es 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