Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

Do not declare read only mutable reference types







Breaking Change

Non Breaking

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

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 (C# Reference) in C#, ReadOnly (Visual Basic) in Visual Basic, and const (C++) in C++) on a reference type field (pointer in C++) 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.

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

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.

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

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();

Community Additions

© 2015 Microsoft