Use Literals Where Appropriate
Use Literals Where Appropriate
Microsoft docsDescription
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 improves 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.
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, static, readonly fields, but this is configurable.
How to fix violations
To fix a violation of this rule, replace the static and readonly modifiers with the const modifier. The use of the const modifier is not recommended for all scenarios.
Example
#pragma warning disable CA1802
// The code that's violating the rule is on this line.
#pragma warning restore CA1802When to suppress
It is safe to suppress a warning from this rule, or disable the rule, if performance is not of concern. For public or externally visible members, changing static readonly to const can lead to issues. const values are embedded in dependent assemblies at compile time, so changes in the library's value might not propagate, potentially causing errors. If the value of your member might change in the future, suppress this rule. Using const is safe for private members and generally safe for internal members unless exposed via InternalsVisibleTo or deployed separately.