I have been trying to wrap my head around this FXCop violation “DoNotDeclareReadOnlyMutableReferenceTypes”
MSDN: http://msdn.microsoft.com/en-us/library/ms182302%28VS.80%29.aspx
Code from MSDN which would cause this violation:
namespace SecurityLibrary
{
public class MutableReferenceTypes
{
static protected readonly StringBuilder SomeStringBuilder;
static MutableReferenceTypes()
{
SomeStringBuilder = new StringBuilder();
}
}
}
From Jon’s answer here and here , I understand that the field holding the reference to the object (in this case SomeStringBuilder) is readonly and not the object itself (which is created by new StringBuilder() )
So taking this example, how would I change the object itself, once the field has a reference to it ? I like Eric Lippert’s example of how the readonly array can be changed, and would like to see something similar for any other mutable reference type
As the MutableReferenceTypes class is presented in the question, you can’t really mutate it from any outside caller since the SomeStringBuilder field is private.
However, the class itself could mutate the field. It doesn’t currently, but it could in a later iteration.
Here’s an example method:
Calling the Mutate method will mutate the class because SomeStringBuilder will now have changed.
Immutability is not only about the current incarnation of your code, but also about protecting yourself from future mistakes. Not that all classes need to be immutable, but it’s safest to stay consistent if you elect to create an immutable type.