Difference between const and readonly

Source: Internet
Author: User

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;

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.