CA2104: Do not declare read only mutable reference types

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
TypeName DoNotDeclareReadOnlyMutableReferenceTypes
CheckId CA2104
Category Microsoft.Security
Breaking Change Non-breaking

Cause

An externally visible type contains an externally visible read-only field that is a mutable reference type.

Rule Description

A mutable type is a type whose instance data can be modified. The System.Text.StringBuilder class is an example of a mutable reference type. It contains members that can change the value of an instance of the class. An example of an immutable reference type is the System.String class. After it has been instantiated, its value can never change.

The read-only modifier (readonly in C#, ReadOnly in Visual Basic, and const in C++) on a reference type field (pointer in C++) prevents the field from being replaced by a different instance of the reference type. However, the modifier does not prevent the instance data of the field from being modified through the reference type.

Read-only array fields are exempt from this rule but instead cause a violation of the CA2105: Array fields should not be read only rule.

How to Fix Violations

To fix a violation of this rule, remove the read-only modifier or, if a breaking change is acceptable, replace the field with an immutable type.

When to Suppress Warnings

It is safe to suppress a warning from this rule if the field type is immutable.

Example

The following example shows a field declaration that causes a violation of this rule.

using namespace System;
using namespace System::Text;

namespace SecurityLibrary
{
    public ref class MutableReferenceTypes
    {
    protected:
        static StringBuilder^ const SomeStringBuilder = 
           gcnew StringBuilder();

    private:
        static MutableReferenceTypes()
        {
        }
    };
}
using System;
using System.Text;

namespace SecurityLibrary
{
    public class MutableReferenceTypes
    {
        static protected readonly StringBuilder SomeStringBuilder;

        static MutableReferenceTypes()
        {
            SomeStringBuilder = new StringBuilder();
        }
    }
}
Imports System
Imports System.Text

Namespace SecurityLibrary

    Public Class MutableReferenceTypes

        Shared Protected ReadOnly SomeStringBuilder As StringBuilder

        Shared Sub New()
            SomeStringBuilder = New StringBuilder()
        End Sub

    End Class

End Namespace