Const and readonly modifier usage, constreadonly

Source: Internet
Author: User

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 }}

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.