Const is a static constant, while const is the compile-time constant. readonly is a dynamic constant and the run-time constant. const is more efficient and readonly is more flexible.
1. by default, const is static and can only be accessed by type. It cannot be used together with static. readonly is non-static by default and accessed by instance objects. It can be displayed as static members;
2. const can only be applied to the value type and string type. Other reference type constants can only be defined as null. Otherwise, a value is assigned to a const reference type constant with "new". readonly read-only fields can be of any type, however, for a reference type field, readonly cannot restrict read/write control on the members of this object instance. The compiler will trigger the "only null pairs can be used for reference types (except strings) initialization error prompt;
3. Const must be initialized when the field is declared; readonly can be declared again, or initialized in the constructor. Different constructor can implement different initial values for readonly constants;
4. const can define fields and local variables, while readonly can only define fields. Static readonly initialization must be performed at the time of definition or in static constructors without parameters;
// Declare Fields
Private const string name = "sssss ";
Private readonly int age = 24;
Private Static readonly string name = "Ssssss ";
// Declare local variables
Public void test ()
{
Const string name = "ddddddd ";
}
5. arrays and struct cannot be declared as const constants, and the string type can be declared as constants. Because of the constant character of the string type, the string value has the read-only attribute;