The concept of const is a variable that contains values that cannot be modified.
A constant expression is an expression that can be fully evaluated at compile-time. Therefore, constants cannot be initialized from values that are extracted from a variable.
If the const int a = B+1;B is a variable, it is obvious that the result cannot be computed at compile time, so constants cannot be initialized with variables.
ReadOnly allows you to set a field to a constant, but you can perform some operations to determine its initial value.
Because ReadOnly is executed at the time of calculation, of course it can be initialized with some variables.
ReadOnly are instance members, so different instances can have different constant values, which makes readonly more flexible.
The ReadOnly keyword differs from the const keyword.
1. The const field can only be initialized in the declaration of the field.
The readonly field can be initialized in a declaration or constructor. Therefore, depending on the constructor used, the ReadOnly field may have different values.
2. The const field is a compile-time constant, and the ReadOnly field can be used to run a constant number.
3. The const default is static, and readonly must display a declaration if it is set to static.
4. Const for a constant of a reference type, the possible value can be only string and null.
ReadOnly can be of any type
Summarize
The readonly field can be initialized in a declaration or constructor function.
The difference between C # const and ReadOnly modifiers