Basic recall: constant data and read-only data are accumulated

Source: Internet
Author: User

Constant field:

1. Constant data modified by const.

2. Constant data must be defined as an initial value.

3. Constant data is static by default.

Example: Public const double Pi = 3.14;

And cannot be modified. If Pi = 222 is displayed, a compilation error is reported.

Read-Only field:

1. Modified by readonly.

2. You do not have to give the initial value when defining it. You can give it in the constructor. In either case, the initial value of readonly can be given.

3. Read-Only fields are not static by default.

For example, public readonly double Pi = 3.14;

Public readonly double PI;

Public mathpi (){

Pi = 3.14;

}

In either case, values cannot be assigned elsewhere. For example:

Public void mathpi () {Pi = 3.14;} Then a compilation error is reported.

I just mentioned that the read-only field is not static by default, so if you want to publicly use the read-only field at the class level, you must explicitly add the static keyword.

Example: public static readonly double Pi = 3.14;

This is similar to the constant field. Of course, if you need to define the parameters first and then assign the initial values to the constructor, you must use the static constructor.

Example: static math (){

Pi = 3.14159;

}

Okay. Recall memories. Can precipitate.

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.