In C#, records are a type of reference type introduced in C# 9.0 that are designed to be lightweight and immutable by default. Immutable means that once you create a record object, its properties cannot be changed. This immutability is enforced by the compiler.
However, starting from C# 9.0, you can make individual properties of a record mutable by using the init keyword. This allows you to set the initial value of the property during object creation, but you won't be able to change it afterwards. Here's an example:
public record Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
// Create a Person object
var person = new Person { FirstName = "John", LastName = "Doe" };
// You can set these properties during object creation
// but you cannot change them afterwards
person.FirstName = "Jane"; // This will result in a compilation error
In this example, the FirstName and LastName properties are mutable during object initialization, but you cannot modify them after the object is created. This allows you to maintain immutability for the record as a whole while still providing some flexibility for property initialization.
So, in summary, records in C# can have mutable properties, but you can control their mutability using the init keyword to enforce immutability once the object is created.
No comments:
Post a Comment