Classes

C# Records

Using Records

C# records provide immutable data with init-only setters.

Introduction to C# Records

C# records, introduced in C# 9.0, are a new reference type that provides a concise way to create immutable data objects. Unlike traditional classes, records are optimized for scenarios where you want to preserve the immutability of data and emphasize the data they contain rather than their behavior.

Defining a Record

Defining a record in C# is straightforward. You use the record keyword followed by the record name and its properties. Here is a simple example:

Benefits of Using Records

  • Immutability: Once a record is created, its data cannot change, promoting safer and more predictable code.
  • Value Equality: Records by default implement value equality, meaning two records are considered equal if their values are equal.
  • Conciseness: Records provide a much more concise syntax compared to traditional classes.

Using Init-Only Setters

Records utilize init-only setters, allowing properties to be set only during initialization. This ensures that once a record is constructed, its state cannot be altered:

Deconstructing Records

Records support deconstruction, a feature that allows extracting values from a record object with ease. Here is an example:

Inheritance with Records

Like classes, records can participate in inheritance. You can derive one record from another, and they will still maintain their immutability and value equality features:

Conclusion

C# records are a powerful feature for defining immutable data containers with minimal syntax. They simplify code and enhance readability while providing the benefits of immutability and value-based equality. This makes records particularly useful in scenarios where data integrity and consistency are paramount.

Previous
Structs