Const defines a static value that is often assigned during object initialization. It cannot be changed later. It is a compilation constant.
Static defines a Static variable. You can change its value externally ..
Readonly is a read-only variable. It belongs to the runtime variable. It can be changed during class initialization ..
Const and static cannot be used together
We all know that const and static readonly are indeed very similar: accessing through the class name rather than the object name, read-only in the program, and so on. In most cases, it can be mixed.
The essential difference between the two is that the const value is determined during compilation, so it can only be specified through a constant expression during declaration. Static readonly calculates the value during running, so it can be assigned through static constructor.
After understanding the essential difference, we can easily see whether static readonly and const can be exchanged in the following statements:
1. static readonly MyClass myins = new MyClass ();
2. static readonly MyClass myins = null;
3. static readonly A = B * 20;
Static readonly B = 10;
4. static readonly int [] constIntArray = new int [] {1, 2, 3 };
5. void SomeFunction ()
{
Const int a = 10;
...
}
1: cannot be changed to const. The new operator needs to execute the constructor, so it cannot be determined during compilation
2: can be changed to const. We can also see that constants of the Reference type (except strings) can only be Null.
3: can be changed to const. We can make it very clear during compilation that A equals 200.
4: cannot be changed to const. The principle is the same as that of 1, although it seems that the arrays of 1, 2, and 3 are indeed constants.
5: you cannot replace it with readonly. readonly can only be used to modify the field of the class. It cannot modify local variables or property.OthersClass member.
Therefore, static readonly can be used for those places that should be essentially constants but cannot be declared using const. Example in C # specification:
Public class Color
{
Public static readonly Color Black = new Color (0, 0, 0 );
Public static readonly Color White = new Color (255,255,255 );
Public static readonly Color Red = new Color (255, 0, 0 );
Public static readonly Color Green = new Color (0,255, 0 );
Public static readonly Color Blue = new Color (0, 0,255 );
Private byte red, green, blue;
Public Color (byte r, byte g, byte B)
{
Red = r;
Green = g;
Blue = B;
}
}
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.
Public static readonly MyClass myins = new MyClass ();
...
Myins. SomeProperty = 10; // normal
Myins = new MyClass (); // error. The object is read-only.
However, if the MyClass in the above example is not a class but a struct, then the following two statements will go wrong.