DoNotDeclareReadOnlyMutableReferenceTypes is a rule that checks for visible read-only fields that are mutable reference types (classes). A mutable type is a type whose instance data can be changed once it has been constructed. For example, the following type is considered mutable:

namespace Microsoft.Samples
{
    
public class Mutable
    {
        
private int _Value;

        
public Mutable(int value)
        {
            _Value = value;
        }

        
public int Value
        {
            
get { return _Value; }
            
set { _Value = value; }
        }
    }
}

Whereas the following type is not, and is therefore considered immutable:

namespace Microsoft.Samples
{
    
public class Immutable
    {
        
private readonly int _Value;

        
public Immutable(int value)
        {
            _Value = value;
        }

        
public int Value
        {
            
get { return _Value; }
        }
    }
}

Although not strictly required, I find it good practice to place the readonly modifier on any member that shouldn’t be changed outside of the constructor.

Unfortunately, due to the complex and costly analysis required to differentiate between a mutable type and an immutable type, DoNotDeclareReadOnlyMutableReferenceTypes, simply fires on any reference type that isn’t in its list of known immutable Framework types.

For example, given the above two types, the following declarations would both be considered violations, even though the Immutable type is immutable:

namespace Microsoft.Samples
{
    
public static class CommonDefaults
    {
        
public static readonly Mutable DefaultMutable = new Mutable(1);             // CA2104: DoNotDeclareReadOnlyMutableReferenceTypes
        public static readonly Immutable DefaultImmutable = new Immutable(1);       // CA2104: DoNotDeclareReadOnlyMutableReferenceTypes
    }
}

However, it is possible to change this. To make DoNotDeclareReadOnlyMutableReferenceTypes aware of your immutable types, simply do the following:

  1. Using a text editor, create a new text file called ImmutableTypes.txt and place this file alongside your FxCop project file, or within the FxCop installation folder.
  2. Using a new line for each type, enter the fully-qualified name of each class you want to mark as immutable, for example:

    Microsoft.Samples.Immutable
    Microsoft.Samples.Immutable1

  3. Save the file and you’re done, FxCop will now consider these classes immutable.

Note: This requires FxCop 1.32 or above.

As always, if you have any questions or issues with FxCop or Managed Code Analysis (including the DoNotDeclareReadOnlyMutableReferenceTypes) head over to the FxCop Forum.