Record vs Class in C#

Muhammad Waseem
Become .NET Pro !
2 min readFeb 7, 2023

A class is a template that combines data and behavior inside a single unit. While record a reference type that was introduced in C# 9 does the same thing like class with some exception that ultimately creates the impact. We use record keyword to create record and class to create classes.

🎯 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞 𝐛/𝐰 𝐫𝐞𝐜𝐨𝐫𝐝 𝐚𝐧𝐝 𝐜𝐥𝐚𝐬𝐬

♉ Record is designed to store the data/properties while classes are supposed to contain logic/operations/behavior.

♉ If you ever compared two instances/objects of class then you would know that those are compared based on their memory objects but record saves us form it, it says I don’t care about some memory stuff, just tell me if property values are same then two records would be called equal. I remember back in old days when I used to write different methods just to compare two objects but now record has saved us.

♉ Record is immutable while classes are not what does it mean it means once record values are initialized, we cannot change them we achieve this by setting our properties of init type but in class we can change them.

♉ Records support non destructive mutation means don’t mess with original but make a copy and enhance it, we achieve it using ‘with’ keyword.

🎯 𝐖𝐡𝐞𝐧 𝐭𝐨 𝐮𝐬𝐞 𝐨𝐧𝐞 𝐨𝐯𝐞𝐫 𝐨𝐭𝐡𝐞𝐫

♉ Use record when your purpose is to contain public data /DTO fancy name. Classes are suitable when it will contain the logic.

♉Record can be suitable choice when you want to store search parameters.

♉ If you want your data to be encapsulated with some complex values and you want one directional flow then go for record otherwise class.

🎯 𝐖𝐡𝐚𝐭 𝐭𝐡𝐞 𝐜𝐨𝐦𝐩𝐢𝐥𝐞𝐫 𝐝𝐨𝐞𝐬 𝐰𝐢𝐭𝐡 𝐜𝐥𝐚𝐬𝐬/𝐫𝐞𝐜𝐨𝐫𝐝
During compile time a class is generated behind the seen for record as well. So, at runtime Class == Record.

If you want to help the author in growing

  1. Subscribe my Weekly .NET Newsletter of C#/.NET
  2. Follow me on LinkedIn/Twitter OR Clap at least 50 times.
  3. Get exclusive .NET Questions & Answers by becoming a Patron.
  4. Download my eBook at Gumroad that contains 30 .NET Tips.

--

--