Visual Basic supports two main ways to declare immutable values — Const and ReadOnly. Const is intended for compile-time constants whose value is known at compile time. ReadOnly allows initialization only at declaration or in the constructor and maintains immutability at runtime.
Historically, even since VB6 and earlier, such semantics allowed avoiding magic numbers and facilitated maintenance. In VB.NET, the capabilities were expanded with the introduction of ReadOnly for instance and class fields.
If you use Const for values that are determined at runtime or depend on external data, errors may occur. Confused scopes can also lead to bugs.
Use Const for simple immutable values (numbers, strings) that are known at compile time, and ReadOnly for cases where the value may be calculated in the constructor but afterward is read-only.
Example code:
Public Class MathConstants Public Const Pi As Double = 3.1415926535 Public ReadOnly Property UtcCreated As DateTime Public Sub New() UtcCreated = DateTime.UtcNow End Sub End Class
Key features:
Can you declare Const for a value obtained at runtime (e.g., from a file)?
No — Const requires a value at compile time. For runtime initialization, ReadOnly should be used.
Can a ReadOnly field be changed after the constructor?
No — modification is only possible at initialization (either at declaration or in the constructor), afterward, it is available only for reading.
Should Const be used for float/double numbers in mathematical calculations?
Yes, if the value is known in advance. However, when used in other assemblies, changing the Const value will require recompilation of all dependent modules since the compiler embeds the value directly.
A developer declared Const for a path to a folder that later had to be changed in different environments (dev/prod). As a result, changing the folder required rebuilding all projects using that Const.
Pros:
Cons:
Implemented ReadOnly for paths, initialized in the constructor considering the environment configuration. Values can be easily changed through settings without rebuilding the entire application.
Pros:
Cons: