What is immutability in C# 9.0?

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.

Explanation

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.

Example

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 properties
Student student = new("Aleena","Ahmend", new string[1] {"92" });
// display reference-type property
Console.WriteLine(student.Marks[0]);
// change value of referenced data
student.Marks[0] = "40";
// display new vlaue
Console.WriteLine(student.Marks[0]);
}
}

Output

92
40

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved