How is the usage of record in C#?
New record types were introduced in C# 9 as an immutable data type to represent values with a set of related properties. Creating and using record types is very simple, here are some common use cases:
- Define the type record.
public record Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
The code above defines a record type called Person, which has two read-only properties: FirstName and LastName.
- Create a record object:
Person person = new Person { FirstName = "John", LastName = "Doe" };
The code above initializes a Person object and sets initial values for its properties.
- Accessing the properties of the record object.
Console.WriteLine(person.FirstName); // 输出:John
Console.WriteLine(person.LastName); // 输出:Doe
The code above accesses the properties of the record object using the dot notation.
- Compare record objects.
Person person1 = new Person { FirstName = "John", LastName = "Doe" };
Person person2 = new Person { FirstName = "John", LastName = "Doe" };
Console.WriteLine(person1 == person2); // 输出:True
The code above compares the values of two record objects using the “==” operator, as the record type automatically implements value comparison logic.
- Update the properties of the record object:
Person updatedPerson = person with { FirstName = "Jane" };
The code above updates the properties of the record object using a with expression, which will return a new record object.
It is important to note that the record type is immutable, meaning once it is created, the values of its attributes cannot be modified. To update attribute values, a new record object must be created using the with expression. This feature makes the record type more suitable for representing immutable data, such as DTOs (Data Transfer Objects) and domain models.