The record keyword is used to create a record class or a record struct. Using the record keyword alone creates a record class and for record structs, use record struct. It can be a readonly struct by using readonly record struct.
- Provides value equality checks based on the values
- Provides a neat implementation of the
ToString()method by default - Allows for non-destructive mutation using the
withkeyword - When you want immutability by default (for positional syntax when using
recordorrecord class)
| Record Declaration Syntax | Property Behavior by Default | Immutability |
|---|---|---|
record Person(string Name); |
get; init; |
Immutable |
record class Person(string Name); |
get; init; |
Immutable |
record struct Point(int X); |
get; set; |
Mutable |
readonly record struct Point(int X); |
get; init; |
Immutable |
Standard body syntax { ... } |
None (Must be explicitly typed) |
Depends on definition |
Creating a record using positional syntax allows for deconstruction.
A record class can only inherit from another record class. It can't inherit from a regular class, nor can a regular class inherit from a record.