CA1802: Use Literals Where Appropriate
|
TypeName |
UseLiteralsWhereAppropriate |
|
CheckId |
CA1802 |
|
Category |
Microsoft.Performance |
|
Breaking Change |
Non-breaking |
The value of a static readonly field is computed at runtime 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 runtime 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 runtime.
The following example shows a type, UseReadOnly, that violates the rule and a type, UseConstant, that satisfies the rule.
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"; } }