Open sandboxFocusImprove this doc

LAMA5020: The field of an immutable type must be read-only

Severity Warning
Reported by Metalama.Patterns.Immutability
Message The '<Field>' field must be read-only because of the [Immutable] aspect.

Cause

The ImmutableAttribute aspect declares that the instances of a type can't be modified after construction. Metalama reports LAMA5020 when such a type declares a field without the readonly modifier, because any code with access to the field could modify it.

1using Metalama.Patterns.Immutability;
2
3namespace Doc.LAMA5020.Error;
4
5[Immutable]
6public class Point
7{
8    // Warning: the field of an immutable type is not read-only.
    Warning LAMA5020: The 'Point.X' field must be read-only because of the [Immutable] aspect.

9    public int X;
10
11    public readonly int Y;
12
13    public Point( int x, int y )
14    {
15        this.X = x;
16        this.Y = y;
17    }
18}
19

Resolution

Add the readonly modifier to the field and assign it only from constructors, as in the following example. If the field must remain writable, the type isn't immutable: remove the [Immutable] aspect.

1using Metalama.Patterns.Immutability;
2
3namespace Doc.LAMA5020.Fixed;
4
5[Immutable]
6public class Point
7{
8    // Fixed: the field is read-only.
9    public readonly int X;
10
11    public readonly int Y;
12
13    public Point( int x, int y )
14    {
15        this.X = x;
16        this.Y = y;
17    }
18}
19

See also