Share via


CA2211: Non-constant fields should not be visible

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 NonConstantFieldsShouldNotBeVisible
CheckId CA2211
Category Microsoft.Usage
Breaking Change Breaking

Cause

A public or protected static field is not constant nor is it read-only.

Rule Description

Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques for synchronizing access to the class object. Because these are difficult skills to learn and master, and testing such an object poses its own challenges, static fields are best used to store data that does not change. This rule applies to libraries; applications should not expose any fields.

How to Fix Violations

To fix a violation of this rule, make the static field constant or read-only. If this is not possible, redesign the type to use an alternative mechanism such as a thread-safe property that manages thread-safe access to the underlying field. Realize that issues such as lock contention and deadlocks might affect the performance and behavior of the library.

When to Suppress Warnings

It is safe to suppress a warning from this rule if you are developing an application and therefore have full control over access to the type that contains the static field. Library designers should not suppress a warning from this rule; using non-constant static fields can make using the library difficult for developers to use correctly.

Example

The following example shows a type that violates this rule.

using System;

namespace UsageLibrary
{
   public class SomeStaticFields
   {
      // Violates rule: AvoidNonConstantStatic;
      // the field is public and not a literal.
      static public DateTime publicField = DateTime.Now;

      // Satisfies rule: AvoidNonConstantStatic.
      public static readonly DateTime literalField = DateTime.Now;

      // Satisfies rule: NonConstantFieldsShouldNotBeVisible;
      // the field is private.
      static DateTime privateField = DateTime.Now;
   }
}

Imports System

Namespace UsageLibrary

Public Class SomeStaticFields
    ' Violates rule: AvoidNonConstantStatic;
    ' the field is public and not a literal.
    Public Shared publicField As DateTime = DateTime.Now
    
    ' Satisfies rule: AvoidNonConstantStatic.
    Public Shared ReadOnly literalField As DateTime = DateTime.Now
    
    ' Satisfies rule: NonConstantFieldsShouldNotBeVisible;
    ' the field is private.
    Private Shared privateField As DateTime = DateTime.Now
End Class 
End Namespace