Differences and relationships between static, const, readonly, and static readonly

Source: Internet
Author: User

1. const Modifier

Initialization time:During compilation, the value has been embedded into the code during compilation;

Value status:Dynamic Modification not allowed

Modification Scope: Field, local variable

Main application scenarios: It is mainly used for variable values that do not need to be changed during the program running, such as the mathematical symbol PI;

2. static Modifier

Initialization time: During running, you can assign values when declaring them, or assign values when using constructors or constructors.

Value status: Allowed to be modified

Modification Scope: The class, field, attribute, method, operator, event, and constructor cannot be used for any type other than the indexer, destructor, or class)

Main application scenarios: Mainly applies to the public attributes of the class.

3. readonly Modifier

Initialization time: During runtime, you can assign values during declaration or assign values to constructors in the class.

Value status: Modification allowed, but can only be modified in the constructor

Modification Scope: Field

Main application scenarios: The read-only attribute of the instantiated object.

4. static readonly Modifier

Initialization time: The runtime is a combination of two keywords.

Value status: Modification allowed. Values are assigned during Declaration or in static constructors.

Modification Scope: Field

Main application scenarios: First, compared with const, it is mainly used for reference variables, while const can only be used for string-type reference variables. Second, the read-only public attribute of the class


This article is from the son of the Sea blog, please be sure to keep this source http://4769069.blog.51cto.com/4759069/1282498

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.