[C#] Immutable vs ReadOnly members

Secure and predictable programming often requires that some data remain constant during program execution. In C#, this can be achieved through the use of Immutable and ReadOnly variables. Although both prevent unwanted modifications, their application and implications are different.

Immutable

An Immutable object is an object whose state cannot be modified after its creation. In C#, this is commonly achieved through the use of classes whose internal state is defined at the time of creation and cannot be altered subsequently.

public class ImmutablePoint{
    public int X { get; }
    public int Y { get; }

    public ImmutablePoint(int x, int y){
        X = x;
        Y = y;
    }
}

In this example, once an ImmutablePoint has been created, its X and Y coordinates cannot be modified.

// Define an immutable object
ImmutablePoint testpoint = new ImmutablePoint(5, 5);

// You can access the members of the instance
Console.WriteLine($"Point: {testpoint.X}, {testpoint.Y}");

// But you cannot modify the members of the instance
testpoint.X = 10; // ERROR

ReadOnly

In C#, a readonly class member is a field that can only be assigned at the time of declaration or within the constructor of the same class. It cannot be changed after the object is created. For value types, the readonly modifier prevents the value from being changed. For reference types, the readonly modifier prevents the reference from being changed, but the objects that they refer to can be modified.

public class ReadOnlyListExample{
    public readonly List ReadOnlyList = new List();

    public ReadOnlyListExample(){
        ReadOnlyList.Add("Hello");
    }
}

ReadOnlyListExample testlist = new ReadOnlyListExample();

// You can add items to the list
testlist.ReadOnlyList.Add("World");
testlist.ReadOnlyList.ForEach(Console.WriteLine);

// But you cannot point another list
testlist.ReadOnlyList = new List(); // ERROR

Vademecum: When to Use Immutable or ReadOnly?

When deciding whether to use Immutable or ReadOnly, consider the following guide:

  • Use Immutable objects when you want the entire object to be constant and its state should not change after creation.
  • Employ ReadOnly variables when you need the value of a specific variable within an object not to change after the object’s initialization.

In general, Immutable objects are useful for ensuring thread safety and for creating code that is easier to reason about, especially in concurrent environments. ReadOnly variables, on the other hand, are optimal when you need to protect individual fields of an object from changes after their initialization, while maintaining the flexibility to modify other fields.


You'll only receive email when they publish something new.

More from GSLF
All posts