|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.|
Use literals where appropriate
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 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.
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