Open sandboxFocusImprove this doc

LAMA5021: The property of an immutable type must not have a setter

Severity Warning
Reported by Metalama.Patterns.Immutability
Message The '<Property>' property must not have a setter because of the [Immutable] aspect.

Cause

The ImmutableAttribute aspect declares that the instances of a type can't be modified after construction. Metalama reports LAMA5021 when such a type declares a non-static automatic property with a set accessor, because the property can be modified at any time. The accessibility of the accessor doesn't matter: a private set accessor also triggers the warning.

Get-only properties, properties with an init accessor, static properties, and properties with an explicit implementation aren't checked.

In the following example, the X property of the immutable Point class has a setter.

1using Metalama.Patterns.Immutability;
2
3namespace Doc.LAMA5021.Error;
4
5[Immutable]
6public class Point
7{
8    // Warning: the automatic property of an immutable type has a setter.
    Warning LAMA5021: The 'Point.X' property must not have a setter because of the [Immutable] aspect.

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

Resolution

Do one of the following:

  • Remove the set accessor and assign the property only from constructors, as in the following example.
  • Replace the set accessor with an init accessor if the property must be settable from object initializers.
  • If the property must remain writable, the type isn't immutable: remove the [Immutable] aspect.

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

See also