There are two types of constants in C #, ReadOnly (run-time) and const (compile-time), and this article compares the different characteristics of these two kinds and describes their respective scenarios.
Working principle
ReadOnly is run at a constant rate, the program is assigned at run time, the assignment is complete and cannot be changed, so it is also called a read-only variable.
Const is a compile-time constant, and when the program compiles, the constants are parsed and all the constant references are replaced with the corresponding values.
Two constants are declared below:
public static readonly int A = 2; A for the running of the constant amount
public const int B = 3; b is a compile-time constant
The following expression:
int C = A + B;
After compilation, it is equivalent to the following form:
int C = A + 3;
As you can see, the const constant b is replaced with literal 3, while ReadOnly constant A is a reference.
Declaration and initialization
The ReadOnly constant can only be declared as a class field, supports instance types or static types, can be initialized at the same time as a declaration, or initialized in a constructor, and cannot be changed after initialization is complete.
The const constant, in addition to being declared as a class field, can also be declared as a local constant in a method, by default to a static type (without the use of static decoration, which would result in a compilation error), but must complete the initialization at the same time as the declaration.
Data type Support
Because the const constant is replaced with a literal at compile time, the value type is limited. Const constants can only be assigned numbers (integers, floating-point numbers), strings, and enumeration types. The following code cannot be compiled by:
Public Const DateTime D = Datetime.minvalue;
Change to ReadOnly can be compiled correctly:
Public readonly DateTime D = Datetime.minvalue;