Compare readonly and const in C #

Source: Internet
Author: User

There are two types of constants in C #, ReadOnly (run-time) and const (compile-time), and this article compares the different characteristics of these two kinds and describes their respective scenarios.

Working principle

ReadOnly is run at a constant rate, the program is assigned at run time, the assignment is complete and cannot be changed, so it is also called a read-only variable.

Const is a compile-time constant, and when the program compiles, the constants are parsed and all the constant references are replaced with the corresponding values.

Two constants are declared below:

public static readonly int A = 2; A for the running of the constant amount

public const int B = 3; b is a compile-time constant

The following expression:

int C = A + B;

After compilation, it is equivalent to the following form:

int C = A + 3;

As you can see, the const constant b is replaced with literal 3, while ReadOnly constant A is a reference.

Declaration and initialization

The ReadOnly constant can only be declared as a class field, supports instance types or static types, can be initialized at the same time as a declaration, or initialized in a constructor, and cannot be changed after initialization is complete.

The const constant, in addition to being declared as a class field, can also be declared as a local constant in a method, by default to a static type (without the use of static decoration, which would result in a compilation error), but must complete the initialization at the same time as the declaration.

Data type Support

Because the const constant is replaced with a literal at compile time, the value type is limited. Const constants can only be assigned numbers (integers, floating-point numbers), strings, and enumeration types. The following code cannot be compiled by:

Public Const DateTime D = Datetime.minvalue;

Change to ReadOnly can be compiled correctly:

Public readonly DateTime D = Datetime.minvalue;

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.