Mutable reference types should not be read-only fields

On the internal FxCop support alias someone asked about the background on the rule that mutable reference types should not be read-only fields… One of the more astute members of the alias was able to quote chapter and verse of the Design Guidelines where it is explained in more detail…

I thought I would share it with you as it is an important and interesting guideline…

            Do not return mutable types from readonly fields. A mutable type is a type whose instance data can be modified (notice arrays and most collections are mutable types). The read-only modifier on a reference type field prevents the field from being replaced by a different instance of the reference type but does not prevent the field's instance data from being modified through the reference type.[1]
The following example shows how it is possible to change the value of a readonly field.

using System;

 

public class F {

   int i;

   public void Change () {

      i++;

   }

   public void Print () {

      Console.WriteLine (i);

   }

}

 

public class Bar {

    public static readonly F f = new F ();

}

public class Foo {

   public static void Main () {

     Bar.f.Change();

    Bar.f.Change();

          Bar.f.Print();

        }

}

Output:

2


[1] Covered by FxCop rule: MutableReferenceTypesShouldNotBeReadOnly