It is possible to create mutable record types by using set
accessors and non-read-only fields. However, records provide a better framework for creating immutable data models.
Immutability is needed when you require a data value to remain unchanged but it is suitable to use everywhere.
init
only setters and positional syntax provide the methods to create immutable data records, but they only provide shallow immutability.
Shallow immutability prevents changes in the values of value-type properties and references of reference-type properties after initialization. However, the data referred to be reference-type properties is still mutable.
The following example demonstrates how the data that a reference-type property refers to remain mutable:
The program creates a record type Student
and initializes its instance. The reference type property here is Marks
, and it references an array. The program changes the value of the array in line 13. When the value of Marks
is displayed after being mutated, it appears to be changed.
using System;public class Program{public record Student(string FirstName, string LastName, string[] Marks);public static void Main(){// create object and initialize propertiesStudent student = new("Aleena","Ahmend", new string[1] {"92" });// display reference-type propertyConsole.WriteLine(student.Marks[0]);// change value of referenced datastudent.Marks[0] = "40";// display new vlaueConsole.WriteLine(student.Marks[0]);}}
92
40
Free Resources