The essential difference is that the const value is determined during compilation, so it can only be specified through a constant expression during declaration. Static readonly calculates its value during running, so it can be assigned a value through a static constructor.
Let's see if the following statements can be exchanged:
1. static readonly testclass test1 = new testclass (); 2. static readonly testclass Test2 = NULL; 3. static readonly A = 20 * B; static readonly B = 2; 4. static readonly int [] array = new int [] {1, 2, 3, 4, 5}; 5. void test () {const int c = 1 ;...}
1: const cannot be changed. The new operator needs to execute the constructor and is determined during execution.
2: it can be changed to const, and the constant of the reference type can be null.
3: It can be changed to const. During the compilation, A = 40.
4: it cannot be changed to const, which is the same as 1.
5: it cannot be changed to readonly. readonly can only be used to modify the field of the class. It cannot modify local variables or other members such as property.
Therefore, static readonly can be used for those places that should be essentially constants but cannot be declared using Const.
Let's look at the following example:
Class program {public static readonly test = new test (); static void main (string [] ARGs) {test. name = "program"; // OK test = new test (); // error :}} class test {public string name ;}
Static readonly requires note that for a reference type of static readonly, the value assignment (write) operation is not allowed. The read and write operations on its members are still unrestricted.