Freigeben über


CA2104: Do not declare read only mutable reference types

Item Value
RuleId CA2104
Category Microsoft.Security
Breaking change Non-breaking

Note

Rule CA2104 is obsolete and will be removed in a future version of Visual Studio. It will not be implemented as an analyzer due to the complicated analysis that's required to determine the actual immutability of a type.

Cause

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

Note

This rule has been deprecated. For more information, see Deprecated rules.

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 (or 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.

This rule may inadvertently show a violation for a type that is, in fact, immutable. In that case, it's safe to suppress the warning.

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's 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 System;
using System.Text;

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

        static MutableReferenceTypes()
        {
            SomeStringBuilder = new StringBuilder();
        }
    }
}