CA1802: Use Literals Where Appropriate

TypeName UseLiteralsWhereAppropriate
CheckId CA1802
Category Microsoft.Performance
Breaking change Non-breaking

Cause

A field is declared static and readonly (Shared and ReadOnly in Visual Basic), and is initialized with a value that is computable at compile time.

By default, this rule only looks at externally visible fields, but this is configurable.

Rule description

The value of a static readonly field is computed at run time when the static constructor for the declaring type is called. If the static readonly field is initialized when it is declared and a static constructor is not declared explicitly, the compiler emits a static constructor to initialize the field.

The value of a const field is computed at compile time and stored in the metadata, which increases run-time performance when it is compared to a static readonly field.

Because the value assigned to the targeted field is computable at compile time, change the declaration to a const field so that the value is computed at compile time instead of at run time.

How to fix violations

To fix a violation of this rule, replace the static and readonly modifiers with the const modifier.

When to suppress warnings

It is safe to suppress a warning from this rule, or disable the rule, if performance is not of concern.

Configurability

If you're running this rule from FxCop analyzers (and not with legacy analysis), you can configure which parts of your codebase to run this rule on, based on their accessibility. For example, to specify that the rule should run only against the non-public API surface, add the following key-value pair to an .editorconfig file in your project:

dotnet_code_quality.ca1802.api_surface = private, internal

You can configure this option for just this rule, for all rules, or for all rules in this category (Performance). For more information, see Configure FxCop analyzers.

Example

The following example shows a type, UseReadOnly, that violates the rule and a type, UseConstant, that satisfies the rule.

Imports System

Namespace PerformanceLibrary

   ' This class violates the rule.
   Public Class UseReadOnly

      Shared ReadOnly x As Integer = 3
      Shared ReadOnly y As Double = x + 2.1
      Shared ReadOnly s As String = "readonly"

   End Class

   ' This class satisfies the rule.
   Public Class UseConstant

      Const x As Integer = 3
      Const y As Double = x + 2.1
      Const s As String = "const"

   End Class

End Namespace
using System;

namespace PerformanceLibrary
{
   // This class violates the rule.
   public class UseReadOnly
   {
      static readonly int x = 3;
      static readonly double y = x + 2.1;
      static readonly string s = "readonly";
   }

   // This class satisfies the rule.
   public class UseConstant
   {
      const int x = 3;
      const double y = x + 2.1;
      const string s = "const";
   }
}