Classes
.NET Records
Using Records
.NET records provide immutable data with init-only setters.
Introduction to .NET Records
.NET Records are a feature introduced in C# 9.0 that allows developers to create immutable data types. They are particularly useful when you want to define a data-centric class with minimal code. Records differ from classes in that they support value-based equality and offer a concise syntax for defining immutable properties.
Defining a Record
Creating a record in .NET is straightforward. You can define a record by using the record
keyword. A record's primary purpose is to deal with immutable data, meaning once a record is created, its data cannot be changed.
Properties with Init-Only Setters
Records make use of init-only properties, which allow properties to be set during object initialization but become immutable afterward. This ensures that the data integrity of a record is maintained after it is instantiated.
Value-Based Equality
Unlike classes, records in .NET are compared based on their values rather than their references. This means two records with the same data are considered equal. This is particularly useful when you need to work with data structures or collections where you need to ensure that two objects are identical in terms of data.
Inheritance with Records
Records support inheritance, which allows you to create a record that inherits from another record. This is useful when you want to extend the functionality of an existing record while maintaining immutability and value-based equality.
Conclusion
.NET Records provide a powerful way to create immutable data types with concise syntax and value-based equality. They are ideal for scenarios where you need to ensure that your data remains unchanged and is compared based on its content rather than its reference. Understanding how to use records effectively can significantly enhance how you manage data-centric applications in .NET.
Classes
- Previous
- Structs
- Next
- Interfaces