What are Records and why should I use them
Title says it all, what are the use cases of them over Objects?
5 Replies
You probably meant to compare them to classes. Some differences:
1 ) Immutability by default
2 ) You will get auto-generated equality overloads which will compare contents by value, and won't compare by reference as the usual behavior would be (Two records, even different references, will be equal if their content is equal)
3) More concise syntax
4) Automatic generation of sensible ToString() output
SharpLab
C#/VB/F# compiler playground.
Check this out, you can effectively see for yourself what the compiler will generate for you
Oh, right, looking over this again: You also get deconstruction syntax support for free
I tend to think of them as the equivalent of what other languages would usually call "data classes" - Not necessarily meant for hosting a lot of data structures or behavior (But you can still embed everything inside if you'd like). The whole immutability factor also encourages them as a data container
Ah
The code in the box below is the code generated from it right?
So is it advised to use Records instead of Classes in case my future Object / class only holds data and does nothing with it?
Not sure how the page is rendered on your side, for me it's on the right - But yeah, the box with all the compiler generated attributes is what your record will transpile into
Honestly, it's hard to give a general rule. I think data containers are the predestined use case for records, but as I mentioned, there's nothing stopping you from adding regular methods and logic to it
If you're just getting started with C#, there's also nothing wrong with using plain old classes until you have a feel for and can appreciate the differences