Do not declare read only fields with mutable reference types

Rule ND1907 Immutability

Violated when a public type contains a public read-only field of a mutable reference type. Misleading: readonly suggests a constant object, but only the reference is fixed — the referenced object's state can still change.

How to fix

Replace the field type with an immutable type, or declare the field private. Severity is Low: more an advice than a problem.

CQLinq source

This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.

// <Name>Do not declare read only fields with mutable reference types</Name>
// <Id>ND1907:DoNotDeclareReadOnlyMutableReferenceTypes</Id>

warnif count > 0 
from f in JustMyCode.Fields where 
  !f.IsStatic &&
   f.IsInitOnly && 
   f.IsPublic &&
   
   f.FieldType != null &&
   f.FieldType.IsClass &&
  !f.FieldType.IsThirdParty &&
  !f.FieldType.IsImmutable
select new { 
   f, 
   f.FieldType, 
   FieldVisibility = f.Visibility,
   Debt = 3.ToMinutes().ToDebt(),
   Severity = Severity.Low
}

//<Expl>
// The *public readonly {0}* is typed with the *{1}* that is mutable: its states can be modified at runtime.
// This situation can be misleading: the keyword *readonly* mistakenly suggests that the object remains constant, 
// while in fact, the field reference remains fixed but the referenced object's state can still change.
// Replace the field type with an immutable class or declare the field as *private*.
//</Expl>

//<Desc>
// Violated when a *public* type contains a *public* read-only field of a
// mutable reference type. Misleading: *readonly* suggests a constant
// object, but only the reference is fixed — the referenced object's state
// can still change.
//</Desc>

//<HowToFix>
// Replace the field type with an immutable type, or declare the field
// *private*. Severity is **Low**: more an advice than a problem.
//</HowToFix>

Immutability: all 15 items