| Severity | Warning |
| Reported by | Metalama.Framework |
| Message | '<Type>' must be written in an immutable style because it is an aspect, a fabric, a validator, or another type bound by the [ImmutableType] contract, but '<MemberType>' is not immutable. Path: <Path>. |
Cause
An aspect is instantiated once and then reused for every declaration to which it applies, and at design time across compilations. State kept in an aspect therefore leaks from one target to the next. For this reason, IAspect and Fabric are marked with the [ImmutableType] attribute, and every type that derives from or implements a marked type, such as every aspect, fabric and validator, must be written in an immutable style. You can also mark your own types with [ImmutableType].
Metalama verifies this contract when it compiles compile-time code. It reports LAMA0882 when a field, or an automatically implemented property, of such a type is of a type that isn't immutable. In the message, <Type> is the type that must be immutable, <MemberType> is the type of the offending member, and <Path> is the chain of declarations that leads from <Type> to the reason why <MemberType> isn't immutable. For example, a path can look like LogAttribute -> _categories -> List<string> (a mutable collection; use the corresponding type of System.Collections.Immutable).
Metalama decides whether a type is immutable as follows:
- Primitive types,
string, enumerations, delegates, and many well-known value types and immutable collections are immutable. A tuple, a nullable value type, or an immutable collection such asImmutableArray<T>is immutable only if its elements or type arguments are. - A class or struct is immutable only if it's marked with
[ImmutableType]. Metalama then verifies the members of this type where it's declared. A type that isn't marked is considered mutable, even if all its fields are read-only. - An array is mutable, because its elements can be replaced, and so are
object,dynamic, and the mutable .NET collections such asList<T>andDictionary<TKey, TValue>. As an exception, an array member of an attribute class, and therefore of an aspect, isn't reported, because C# requires a collection-valued attribute argument to be an array. - A type parameter is immutable inside the generic definition. The obligation moves to the code that supplies the type argument, and a constructed generic type such as
Box<StringBuilder>is reported if the type stores that argument.
Metalama reports each member once. If the member is also writable from outside the type, LAMA0880 or LAMA0881 is reported instead, and you must fix it before this one. Members that are templates or introduced by the aspect, such as members marked [Template] or [Introduce], are exempt because they describe code generated in the target. When the member type is an interface or an abstract class that isn't marked, Metalama reports LAMA0884 instead.
In the following example, the Log aspect stores the categories passed to its constructor in a List<string> field.
1using Metalama.Framework.Aspects;
2using System;
3using System.Collections.Generic;
4
5namespace Doc.LAMA0882.Error;
6
7public class LogAttribute : OverrideMethodAspect
8{
9 // Warning: List<string> is a mutable collection.
Warning LAMA0882: 'LogAttribute' must be written in an immutable style because it is an aspect, a fabric, a validator, or another type bound by the [ImmutableType] contract, but 'List<string>' is not immutable. Path: LogAttribute -> _categories -> List<string> (a mutable collection; use the corresponding type of System.Collections.Immutable).
10 private readonly List<string> _categories;
11
12 public LogAttribute( params string[] categories )
13 {
14 this._categories = new List<string>( categories );
15 }
16
17 public override dynamic? OverrideMethod()
18 {
19 var categories = string.Join( ", ", this._categories );
20 Console.WriteLine( $"[{categories}] Entering {meta.Target.Method}." );
21
22 return meta.Proceed();
23 }
24}
25
1namespace Doc.LAMA0882.Error;
2
3internal class OrderService
4{
5 [Log( "Orders", "Billing" )]
6 public void PlaceOrder( string product, int quantity )
7 {
8 // Places the order.
9 }
10}
11
1using System;
2
3namespace Doc.LAMA0882.Error;
4
5internal class OrderService
6{
7 [Log("Orders", "Billing")]
8 public void PlaceOrder(string product, int quantity)
9 {
10 Console.WriteLine("[Orders, Billing] Entering OrderService.PlaceOrder(string, int).");
11
12 // Places the order.
13 }
14}
15
Resolution
Choose the option that suits the member:
- Replace the mutable type with an immutable one:
ImmutableArray<T>instead of an array orList<T>,ImmutableDictionary<TKey, TValue>instead ofDictionary<TKey, TValue>, and so on. Make sure that the elements are immutable too. - If the type is yours, mark it with
[ImmutableType]and make all its instance fields read-only and immutable. Metalama verifies it. - If the type isn't yours and you know that it's immutable, declare it with a
MetalamaImmutableTypeitem in the project file, using the full metadata name of the type, with its arity for a generic type (see LAMA0885). - If the member holds state that depends on the target of the aspect, don't store it in the aspect at all. Compute it in
BuildAspector in the template instead. - If the warning is unwanted on one declaration, suppress it with
#pragma warning disable LAMA0882. If your project implements the framework itself, set theMetalamaEnforceImmutabilityContractMSBuild property tofalse.
In the following example, the field is an ImmutableArray<string>, which can't be modified after construction.
1using Metalama.Framework.Aspects;
2using System;
3using System.Collections.Immutable;
4
5namespace Doc.LAMA0882.Fixed;
6
7public class LogAttribute : OverrideMethodAspect
8{
9 // Fixed: ImmutableArray<string> can't be modified after construction.
10 private readonly ImmutableArray<string> _categories;
11
12 public LogAttribute( params string[] categories )
13 {
14 this._categories = ImmutableArray.Create( categories );
15 }
16
17 public override dynamic? OverrideMethod()
18 {
19 var categories = string.Join( ", ", this._categories );
20 Console.WriteLine( $"[{categories}] Entering {meta.Target.Method}." );
21
22 return meta.Proceed();
23 }
24}
25
1namespace Doc.LAMA0882.Fixed;
2
3internal class OrderService
4{
5 [Log( "Orders", "Billing" )]
6 public void PlaceOrder( string product, int quantity )
7 {
8 // Places the order.
9 }
10}
11
1using System;
2
3namespace Doc.LAMA0882.Fixed;
4
5internal class OrderService
6{
7 [Log("Orders", "Billing")]
8 public void PlaceOrder(string product, int quantity)
9 {
10 Console.WriteLine("[Orders, Billing] Entering OrderService.PlaceOrder(string, int).");
11
12 // Places the order.
13 }
14}
15