Const and readonly modifier usage, constreadonly
1. Only C # built-in types (int, double, long, etc.) can be declared as const; results, classes, and arrays cannot be declared as const.
2. readonly is the modifier used on the field, which is directly accessed by class name. Field.
3. const must be initialized in the Declaration. It cannot be modified later.
4. readonly can be initialized in the Declaration or in the constructor. It cannot be modified in other cases.
Namespace const_and_readonly {class Program {static void Main (string [] args) {Console. writeLine ("Half a year have {0} Moths", Calendar. moths/2); // direct class name. field access const field Calendar test1 = new Calendar (); Console. writeLine ("Every year has {0} weeks and {1} days", test1. _ weeks, test1. _ days ); // The readonly field accesses the Calendar test2 = new Calendar (31, 4) through the instance; Console. writeLine ("January has {0} weeks and {1} days", test2. _ weeks, test2. _ days); Console. readKey () ;}} class Calendar {public const int Moths = 12; // const must be initialized in the Declaration public readonly int _ days = 365; // readonly initializes public readonly int _ weeks in the Declaration; public Calendar () // readonly initializes {_ weeks = 52;} public Calendar (int days, int weeks) // readonly initialization in the constructor {_ days = days; _ weeks = weeks;} public void setvalue (int days, int weeks) {// _ days = days; the value of read-only fields cannot be assigned // _ weeks = weeks; the value of read-only fields cannot be assigned }}