ado| Difference
As we all know, the const and static readonly are very similar: accessed through class names rather than object names, read-only in programs, and so on. Can be mixed in most cases.
The essential difference between the two is that the const value is determined during compilation, so the value can only be specified by a constant expression at the time of declaration. While the static readonly is computed at runtime, it can also be assigned by static constructors.
Knowing this essential distinction, it is not difficult to see whether the static readonly and const can be interchanged in the following statement:
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: Can not change to Const. The new operator is required to perform a constructor, so it is not possible to determine during compilation
2: You can change to Const. We also see that constants of type reference (except string) can only be null.
3: You can change to Const. We can make it clear at compile time that a equals 200.
4: Can not change to Const. The truth is the same as 1, although it looks like the 1,2,3 array is indeed a constant.
5: Can not be changed to Readonly,readonly can only be used to modify the field of the class, can not modify local variables, and can not modify the property and other class members.
Therefore, you can use static readonly for places that are inherently constant, but cannot be declared using Const. Examples given in the C # specification are as follows:
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;
}
}
One problem that static readonly need to be aware of is that for a static readonly reference type, it is only limited to the assignment (write) operation. The reading and writing of its members is 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 example above is not a class but a struct, then the following two statements will be faulted.